【发布时间】:2019-07-03 17:26:38
【问题描述】:
最后一个 else 语句不会打印任何内容... 只需输入并停止程序。我做错了什么?
我是全新的,刚开始学习java。没有任何代码方面的经验。对不起。
尝试检查语法,“我的菜鸟眼睛”看起来一切正常
import java.util.Scanner;
public class MyClass
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int x =7;
System.out.println("Enter a Number from 1 to 10: ");
int guess = scn.nextInt();
while(x != guess)
{
if(x < guess) {
System.out.println("Guess Lower...");
guess = scn.nextInt();
}
else if (x > guess) {
System.out.println("Guess Higher...");
guess = scn.nextInt();
}
else {
System.out.println("Correct Guess!");
}
}
}
}
所以如果我输入 7 它应该说/显示 猜对了!
但它不会显示任何内容。
不过,猜测低和高都可以。
【问题讨论】:
-
这是您的
while条件。它在else块有机会运行之前跳出循环。 -
但最后一个 else 包含在其中,不是吗?
-
@S.S.不,最后一个 else 在 if 内,而不是 while
-
哦,好吧,所以 x 变成 = guess,在这种情况下它混淆了 while 条件,即 while x is NOT eq to guess?
-
@S.S 我认为@liya Bursov 想说的是,最后一次执行
else的唯一时间是x == guess。但是,您的 while 循环仅在x != guess时运行。
标签: java if-statement