gpt4 book ai didi

java - 数学加法代码,尝试在正确答案后结束

转载 作者:行者123 更新时间:2023-12-02 03:02:25 24 4
gpt4 key购买 nike

我遇到的问题是,在正确回答后,它仍然提出问题。我缺少什么?我现在对 JAVA 还很陌生,不想因为一个简单的错误或疏忽而气馁。

package acourtney;

import java.util.Scanner;

public class Hmwk03 {

public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
int counter = 0;

Scanner input =new Scanner(System.in);

System.out.print ("What is " + number1 + " + " + number2 + " ? " + "(You have three chances) ");

int answer = input.nextInt();

if (number1 + number2 == answer)
System.out.println("Answer is correct");

else
System.out.println("Your answer is incorrect. You have two chances left ");
counter = 2;

System.out.print("What is " + number1 + " + " + number2 + " ? ");

answer = input.nextInt();

if (number1 + number2 == answer)

System.out.println("Answer is correct");

else
System.out.println("Your answer is incorrect. You have one chance left");
counter = 3;

System.out.print("What is " + number1 + " + " + number2 + " ? ");

answer = input.nextInt();

if (number1 + number2 == answer)
System.out.println("Answer is correct");

else
System.out.println("Your answer is incorrect, You have failed");

}


}

最佳答案

作为 Java 初学者,我建议您对程序进行伪代码,以便为自己提供一个工作蓝图。它可以帮助您将代码分解为更小的步骤。

public class Hmwk03 {

public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
int counter = 2; // Define the number of chances they have, start at 2 since the first counter value is 0
boolean answerCheck = false; // Define if they answer was right

Scanner input =new Scanner(System.in);

// Generate a for loop with a counter starting at 0
// The loop will run either if they have more chances left
// OR when they have gotten the answer right
for(int i = 0; i < counter || answerCheck == true; i++) {

System.out.print ("What is " + number1 + " + " + number2 + " ? " + "(You have three chances) "); // Output the question

int answer = input.nextInt(); // Receive the answer

if (number1 + number2 == answer) { // if they got the right ansser
// Make the answerCheck true or use break here
answerCheck = true;
System.out.println("Answer is correct"); // Output the user got the correct answer
//break; This will also work to end the loop
} else { // they got the wrong answer
System.out.println("Your answer is incorrect. You have " + counter - i + " chances left."); // Note they got the answer wrong and tell them how many chances they have left
}
}
if(!answerCheck) System.out.print(" You have failed"); // If they failed to get the answer correct, print out final statement.

}

关于java - 数学加法代码,尝试在正确答案后结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263354/

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