问题描述
我正在尝试创建Java猜谜游戏,但是我正在研究的第一部分存在问题,我需要一些帮助。 该程序首先要求用户输入一个数字,然后程序要求他们确认他们的数字是否是他们输入的数字。
如果输入的是“是否输入正确的数字”,则当前仅输出“ bru”。
如果没有输入,则他们将重新输入输入的数字,并且该循环将继续进行,直到用户正确输入其数字并确认为止。
我正在尝试通过while
循环来实现这一点。
不幸的是,当我运行程序时,一切正常,直到要求我输入yes或no确认我的电话号码为止。如果我输入是,它仍然会要求我重新输入数字。 但是,如果我输入no,然后我再说一次no确认我的号码,当我确认输入正确的号码时,它会为我提供输出。
import java.util.Scanner;
import java.util.Random;
public class Assignment6 {
public static void main(String args[]) {
Scanner input = new Scanner( system.in );
System.out.print ( "Please enter the upper bound of the secret number.");
int UpperBound = input.nextInt();
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes,if not please enter no.");
String TrueOrFalse = input.next();
while (TrueOrFalse == "no" | TrueOrFalse == "No");
{
System.out.print ( "Please enter the new upper bound of the secret number.");
UpperBound = input.nextInt();
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes,if not please enter no.");
TrueOrFalse = input.next();
}
System.out.print ("Bru");
}
}
解决方法
替换
ScrollView
使用
while (TrueOrFalse == "no" | TrueOrFalse == "No");
即从那一刻删除while(TrueOrFalse.equalsIgnoreCase("no"))
还尽可能重命名变量;
您的主要问题是 ;
,并使用equals and ==
比较String。
您还需要检查nextInt() and nextLine()
之间的差异
尝试以下代码,它将为您提供帮助。
public static void main(String args[]) {
Scanner input = new Scanner( System.in );
System.out.print ( "Please enter the upper bound of the secret number.");
int UpperBound = Integer.valueOf(input.nextLine());
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes,if not please enter no.");
String TrueOrFalse = input.nextLine();
while (TrueOrFalse.equalsIgnoreCase("no"))
{
System.out.print ( "Please enter the new upper bound of the secret number.");
UpperBound = Integer.valueOf(input.nextLine());
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes,if not please enter no.");
TrueOrFalse = input.nextLine();
}
System.out.print ("Bru");
}