我对+ =赋值运算符的工作方式感到有些困惑。我知道x + = 1是x = x + 1。但是,在此代码中有一个名为“String output”的字符串变量,并使用空字符串进行初始化。我的困惑是变量'输出'有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);
}
}
答案 0 :(得分:1)
答案 1 :(得分:0)
添加AND赋值运算符。
它将右操作数添加到左操作数并将结果赋给左操作数。
在你的情况下
output += someString // output becomes output content +somestring content.
`
答案 2 :(得分:0)
也许写出了正确的答案,但如果我理解你的问题,你需要澄清而不是+ =
的意思更改代码;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
这样:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
所以你可以一起看到线和计数。然后按你的意愿增加。
在Java中,字符串是不可变的。所以output += somethingNew
就是这样的:
String temp = output;
output = temp + somethingNew;
最后,它变得像concat / merge