【发布时间】:2017-02-17 23:26:41
【问题描述】:
我是一名 Java 初学者,正在阅读 First head Java 书籍。 我确实管理了这本书的要求,但我正在努力改进程序
该程序应该生成一个介于 0-7 之间的随机数,然后将其放入一个包含以下两个数字的数组,用户必须猜测它。 一切正常,除了我试图限制用户输入除 0 到 7 之间的数字以外的任何内容
这是我的尝试,我不知道为什么它不起作用:
public String checkYourSelf (String stringGuess){
String result = "miss"; //this will be returned if the guess doesn't match
if (stringGuess != "0" ||
stringGuess != "1" ||
stringGuess != "2" ||
stringGuess != "3" ||
stringGuess != "4" ||
stringGuess != "5" ||
stringGuess != "6" ||
stringGuess != "7" ){
System.out.println("Please Enter a correct number");
result = "error";
return result;
}
然后我使用 parseInt 方法
int guess = Integer.parseInt(stringGuess);
整个方法:
public String checkYourSelf (String stringGuess){
String result = "miss"; // this will be returned if the guess doesn't match
if (stringGuess != "0" ||
stringGuess != "1" ||
stringGuess != "2" ||
stringGuess != "3" ||
stringGuess != "4" ||
stringGuess != "5" ||
stringGuess != "6" ||
stringGuess != "7" ){
System.out.println("Please Enter a correct number");
result = "error";
return result;
}
int guess = Integer.parseInt(stringGuess);
for (int cell : cellsLocations) {
if (enterdNums.contains(guess)){
result = "error";
System.out.println ("You've entered this number already.");
System.out.println("Please try again");
break;
}
if (cell == guess) {
result = "hit";
hits++;
break;
}
}
if (hits == cellsLocations.length) {
result = "kill";
}
if (result != "error"){
System.out.println(result);
}
enterdNums.add(guess); // add to the list so it doesnt
return result;
}
}
在主方法中:
while (isAlive) {
guess = input.getUserInput("Enter a number");
result = dot.checkYourSelf(guess);
if (result == "error"){
continue;
}
numOfGuesses++;
if (result == "kill"){
System.out.println(numOfGuesses);
isAlive = false;
break;
}
}
我知道可能有其他方法可以做到这一点,但我正在尝试使用我已经知道的东西来做到这一点,从逻辑上讲这应该可以工作,但是如果我输入任何数字,它会说“请输入正确的数字"
谢谢
【问题讨论】:
-
另外,您的 OR (
||) 应该是 AND (&&)。任何值都不等于其中一个值。 -
一个建议......永远不要在字符串中使用 '==',使用 equals() 或 equalsIgnoreCase()
标签: java if-statement methods operators