我正在编写一个程序,该程序遵循以下说明:
你妹妹让你帮她做乘法,然后你决定写一个Java程序来测试她的技能。这个程序会让她输入一个起始数,比如5。它会产生10个乘法问题,从5×1到5×10不等。对于每一个问题,她都会被提示输入正确的答案。该程序应检查她的答案,不应让她进入下一个问题,直到正确的答案给出当前的问题。 在测试了十个乘法问题之后,你的程序应该问她是否愿意尝试另一个起始数。如果是,你的程序应该会产生另一个相应的十个乘法问题。这个程序应该重复,直到她表示不同意为止。
我有正确的代码要求乘法部分,但我不太清楚如何让程序问用户是否想继续。
以下代码只运行一次程序:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
}
}当我取消对第21行的注释时,程序返回:
输入您想要尝试的号码:1 1x1=1 你想做另一个问题吗?1x2=2 你还想做别的问题吗?1x3=等等.
如果我将第21行的代码放在for循环之外,程序只运行一次for循环,然后直接跳到问题上。
我如何着手解决这个问题,并成功地完成说明?
发布于 2015-11-29 20:33:49
我是这样做的:
package hw5;
import java.util.Scanner;
public class HW5 {
public static void main(String[] args)
{
boolean wantsToContinue = true;
while(wantsToContinue)
{
wantsToContinue = mathProblem();
}
}
public static boolean mathProblem()
{
Scanner input = new Scanner(System.in);
System.out.print("Enter number you would like to attempt: ");
int start = input.nextInt();
int mult;
for (mult = 1; mult <= 10; mult++) {
int num = start * mult;
System.out.print(start + " x " + mult + " = ");
int ans = input.nextInt();
while (ans != num) {
System.out.print("Wrong answer, try again: ");
int ans2 = input.nextInt();
if (ans2 == num) {
break;
}
}
//System.out.print("Would you like to do another problem? ");
}
boolean wantsToContinue;
//Ask if the user would like to do another problem here, set "wantsToContinue" accordingly
return wantsToContinue;
}
}https://stackoverflow.com/questions/33987507
复制相似问题