-5

我正在用 Java 做一个简单的测验,但是我遇到了一些麻烦。

import java.util.Scanner;
public class quiz {
    public static void main( String[] args ) {
        Scanner keyboard = new Scanner( System.in );
        String q1 = "London";
        String a1;
        int q2 = 20;
        int a2;
        String q3 = "Java";
        String a3;
        int score = 0;

        System.out.println( "What is the capital of England? ");
        a1 = keyboard.next();
        if(a1 == q1) {
            score + 1;
            System.out.println( "Correct!");
        }
        else if {
            System.out.println( "WRONG!" );
        }

        System.out.println( "What is 10 + 10?" );
        a2 = keyboard.nextInt();
        if(a2 == q2) {
            score + 1;
            System.out.println( "Correct!" );
        }
        else if {
            System.out.println( "WRONG" );
        }

        System.out.println( "What langauge is kevin learning?" );
        a3 = keyboard.next();
        if(a3 == q3) {
            score + 1;
            System.out.println( "Correct!" );
        }
        else if {
            System.out.println( "WRONG" );
        }

        System.out.println( "Your total marks were" score );
    }
}
4

2 回答 2

2

你必须使用他们的equals方法来比较==String,而不是比较String,而是对象在内存中的位置。所以,而不是if(a1 == q1)使用if(a1.equals(q1))

编辑:这是工作代码:

import java.util.Scanner;

public class quiz {
  public static void main( String[] args ) {
        Scanner keyboard = new Scanner( System.in );
        String q1 = "London";
        String a1;
        int q2 = 20;
        int a2;
        String q3 = "Java";
        String a3;
        int score = 0;

        System.out.println( "What is the capital of England? ");
        a1 = keyboard.next();
        if(a1.equals(q1)) {
            score += 1;
            System.out.println( "Correct!");
        }
        else {
            System.out.println( "WRONG!" );
        }

        System.out.println( "What is 10 + 10?" );
        a2 = keyboard.nextInt();
        if(a2 == q2) {
            score += 1;
            System.out.println( "Correct!" );
        }
        else {
            System.out.println( "WRONG" );
        }

        System.out.println( "What langauge is kevin learning?" );
        a3 = keyboard.next();
        if(a3.equals(q3)) {
      score += 1;
            System.out.println( "Correct!" );
        }
    else {
            System.out.println( "WRONG" );
        }

    System.out.println("Your total marks were" + score);
    }
}
于 2013-07-25T10:39:50.033 回答
1

不正确的String比较:

if(a1 == q1)

应该:

if(a1.equals(q1))

同样的故事:

if(a3 == q3)
于 2013-07-25T10:38:45.187 回答