1

我对 += 赋值运算符的工作方式有点困惑。我知道 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);

    }


 }
4

3 回答 3

1

Badshah 给出的答案对您的程序很重要,如果您想了解更多关于操作员的可用性,请查看我遇到的这个问题

+ Java中字符串的运算符

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

于 2013-06-18T19:41:48.470 回答
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 的东西

于 2013-06-18T19:39:43.780 回答
0

它的Add AND 赋值运算符

它将右操作数添加到左操作数并将结果分配给左操作数。

在你的情况下

output += someString // output becomes output content +somestring content.

`

于 2013-06-18T19:09:44.733 回答