我正在用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 );
}
}
答案 0 :(得分:2)
您必须使用equals
方法比较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);
}
}
答案 1 :(得分:1)
String
比较不正确:
if(a1 == q1)
应该是:
if(a1.equals(q1))
同样的故事:
if(a3 == q3)