gpt4 book ai didi

java - 乘法导师Java程序

转载 作者:行者123 更新时间:2023-12-01 10:49:38 25 4
gpt4 key购买 nike

我正在编写一个遵循以下说明的程序:

Your little sister asks you to help her with her multiplication, and you decide to write a Java program that tests her skills. The program will let her input a starting number, such as 5. It will generate ten multiplication problems ranging from 5×1 to 5×10. For each problem she will be prompted to enter the correct answer. The program should check her answer and should not let her advance to the next question until the correct answer is given to the current question.

After testing ten multiplication problems, your program should ask whether she would like to try another starting number. If yes, your program should generate another corresponding ten multiplication problems. This procedure should repeat until she indicates no.

我有正确的代码来询问乘法部分,但我不太清楚如何让程序询问用户是否要继续。

以下代码使程序运行一次:

    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 行的注释时,程序返回:

Enter number you would like to attempt: 1

1 x 1 = 1

Would you like to do another problem? 1 x 2 = 2

Would you like to do another problem? 1 x 3 =

etc...

如果我从第 21 行取出代码并将其放在 for 循环之外,程序将运行 for 循环一次,然后直接跳到问题。

我该如何解决此问题并成功完成说明?

最佳答案

我的做法是这样的:

    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;
}
}

关于java - 乘法导师Java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com