gpt4 book ai didi

Java关于+=赋值运算符的澄清

转载 作者:太空宇宙 更新时间:2023-11-04 07:34:21 25 4
gpt4 key购买 nike

我对 += 赋值运算符的工作原理有点困惑。我知道 x += 1 是 x = x+1。但是,在此代码中,有一个名为“字符串输出”的字符串变量,并使用空字符串进行初始化。我的困惑是变量“输出”有 5 个不同的输出,但我不知道它存储在哪里。帮忙澄清一下我的误解。我似乎无法弄清楚。

import java.util.Scanner;

public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);

while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);

// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}

// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();

// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));


// Increase the question count
count++;

output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");

}

long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;

System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);

}


}

最佳答案

Badshah 给出的答案对于您的程序来说是值得赞赏的,如果您想了解更多有关运算符(operator)可用性的信息,请查看我遇到的这个问题

+ operator for String in Java

发布的答案有很好的运营商推理

关于Java关于+=赋值运算符的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176906/

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