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 の String 演算子

投稿された回答には、オペレーターの非常に適切な理由があります

于 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 に答える