gpt4 book ai didi

java - 如何控制用户输入的内容?

转载 作者:行者123 更新时间:2023-12-01 06:07:03 24 4
gpt4 key购买 nike

我是一名 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;
}
}

我知道可能还有其他方法可以做到这一点,但我正在尝试用我已经知道的东西来做到这一点,从逻辑上讲,这应该可行,但是如果我输入任何数字,它会说“请输入正确的数字” ”

谢谢

最佳答案

使用 while 循环。其简单且易于实现

guess = input.getUserInput("Enter a number");
while(guess < 0 || guess > 7){
System.out.println("that number is invalid! Enter a number 0-7 : ");
guess = input.getUserInput("Enter a number");
}

循环将迭代,直到用户输入 0-7 之间的数字

关于java - 如何控制用户输入的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42309131/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com