我有一个Java类的作业,用于编写Magic 8-ball。它应该为响应生成一个随机数,包含一个“while(true)”语句,以及一个用于回复的switch语句。这就是我到目前为止所拥有的。我似乎无法弄清楚如何在没有无限重复的情况下使用“while(true)”语句。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String question;
int retry;
int q1;
System.out.print("What is your question for the Magic 8-bit 8-ball? ");
question = input.next();
System.out.print(process());
/*This is where I am having the problem. How do I work a "while(true)" in
* to where this won't infinitely repeat?
*/
}
public static int process() {
Random rand1 = new Random();
int random = rand1.nextInt(9);
int ans = random;
switch (ans) {
default: System.out.println("Does not compute!! Error! Error!");break;
case 1: System.out.println("The answer is.............. 42");break;
case 2: System.out.println("To get to the other side!!!");break;
case 3: System.out.println("Out of memory! Try again!");break;
case 4: System.out.println("Who do you think I am, IBM's Watson?");break;
case 5: System.out.println("Danger Will Robinson!! Danger!!");break;
case 6: System.out.println("What do you think?");break;
case 7: System.out.println("Fatal error.....nahhh just kidding");break;
case 8: System.out.println("Well, this is fun....NOT!");break;
case 9: System.out.println("Um...... 1,000,000,000,000,000,000,000?");break;
}
return ans;
}
}
答案 0 :(得分:1)
嗯,pinContent
循环的要点是无限的,除非你在其中添加while (true)
语句。
break
请注意,这相当于
while (true) {
doStuff();
// if someCondition is true, this will exit the loop
if (someCondition)
break;
}
或
do {
doStuff();
} while (!someCondition);
不通常更喜欢无限循环(例如boolean someCondition = false;
while (!someCondition) {
doStuff();
}
)并且具有明确的条件。存在一些例外情况,例如,如果条件表达复杂,或者您想要在循环的特定位置而不是在开头或结尾处打破循环:
while (true)
答案 1 :(得分:0)
许多可能的方法之一:
while (true) {
doStuff();
if (someCondition)
break;
doSomeOtherStuff();
}
(即'Y'
)。 char continueLoop = 'Y'
)。while(char == 'Y')
,然后使用System.out.println("Continue? Y/N")
读取输入并将其指定给continueLoop。您可以使用布尔值创建类似的内容。