你好,我是一名初学Java程序员。当我输入正确的数字(没有打印消息)时,我的程序会一直结束,或者它不会从较低的数字变为较高的数字而不会结束? 有人能告诉我我做错了吗?
package week3;
import java.util.Scanner;
public class Week3 {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
int Guess ;
int count = 0;
count++;
int c = 55;
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
System.out.print("Enter your guess: ");
Guess = In.nextInt();
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
}//end if
while (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//End while < 1
while (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
Guess = In.nextInt();
}//end while <100
while (Guess >= 56)
{
System.out.println("The number is lower.");
Guess = In.nextInt();
} //end while over 55
while (Guess <= 54)
{
System.out.println("The number is higher.");
Guess = In.nextInt();
}//end while lower than 55
}//end main
}//end class
答案 0 :(得分:1)
我可以看到问题所在,但您最好自己尝试找到它。 (或者另外去......)
提示:
尝试手动执行代码。假装你是电脑,并用铅笔和纸来模拟它会做什么。
您是否尝试过使用调试器?
有些评论也是很好的提示。
虽然我有你的耳朵,你也应该注意你的编程风格。 Java的一个通用样式规则是变量应该以小写字母开头。您的In
和Guess
变量违反了这一点。
答案 1 :(得分:0)
System.out.println("Welcome to the Higher / Lower game! Try to guess the"
+ "number between 1 and 100. ");
while (true) {
System.out.print("Enter your guess: ");
Guess = Integer.parseint(In.nextLine());
if(Guess == c)
{
System.out.println("The number was 55 you guessed correctly! "
+ " it took you " + count +" tries");
break;
}
if (Guess < 1)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess > 100)
{
System.out.println("Sorry, the guess needs to be a number between 1 and"
+ " 100. Please try again:");
}
if (Guess >= 56)
{
System.out.println("The number is lower.");
}
if (Guess <= 54)
{
System.out.println("The number is higher.");
}
}
}
}
希望这能让您了解使用while循环的想法。
答案 2 :(得分:0)
您的程序结构不正确。
循环时只需要一个。使用while循环开始您的程序,并继续条件,例如:
boolean numFound = false;
while (!numFound) {
//conditions
}