因此,对于我的java程序,我需要编写一个带有if else语句的while循环,该语句允许输入对季节的猜测,这是通过将一个季节分配给从1到4生成的数字而随机生成的当我编译时,我没有得到任何错误,但是当我执行程序时,我得到所有猜测的零。数字生成中是否有一些我缺失的东西?或者是字符串比较?
编辑:代码现在按预期工作。我明白我做错了什么。感谢那些帮助过的人。
以下是所需的代码和变量:
public class SeasonsGenerator {
public static void main(String[] args){
//Variables for seasons counter
int summerSeasonCounter=0;
int fallSeasonCounter=0;
int springSeasonCounter=0;
int winterSeasonCounter=0;
int number;
int limit = 5;
Scanner keyboard = new Scanner(System.in);
int count = 0; // Counter for total number of iterations or loops
String season = "";//Variable for season
final int NUMBER = 15; // Number of while loop iterations
String userGuess;//save user guess here
// A random number generator
Random generator = new Random();
while(count < NUMBER)
{
number = generator.nextInt(limit);
if(number == 1)
{
season = "summer";
}
else if(number == 2)
{
season = "spring";
}
else if(number == 3)
{
season = "fall";
}
else if(number == 4)
{
season = "winter";
}
System.out.print("Guess the season generated by the random number generator:");
userGuess = keyboard.nextLine();
userGuess.equalsIgnoreCase(season);
if(season == "summer")
{
summerSeasonCounter +=1;
}
else if(season == "spring")
{
springSeasonCounter += 1;
}
else if(season == "fall")
{
fallSeasonCounter += 1;
}
else if(season == "winter")
{
winterSeasonCounter += 1;
}
// Display the results
System.out.println ("You guessed Summer season correctly "+summerSeasonCounter+" number of times.");
System.out.println ("You guessed Fall season correctly "+fallSeasonCounter+" number of times.");
System.out.println ("You guessed Spring season correctly "+springSeasonCounter+" number of times.");
System.out.println ("You guessed Winter season correctly "+winterSeasonCounter+" number of times.");
}
}
答案 0 :(得分:2)
您遇到了许多问题,我建议您通过调试器运行代码以帮助您找到错误。一些明显的错误是
season.equals("summer");
将赛季与“夏天”进行比较并返回false。它没有指定任何东西。if (userGuess.equalsIgnoreCase(season))
四次。如果第一次是假的,那么四次都是假的。您当前的问题是要分配一个需要使用=
season = "summer";