如何解决简单命令行程序中的奇怪行为
我正在尝试创建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");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。