2013-07-25 81 views
-4

我正在Java中進行一個簡單的測驗,但是,我遇到了一些麻煩。Java測驗不工作需要if語句的幫助

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); 
    } 
} 
+1

什麼是*有些麻煩*? –

+0

可能的重複[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –

+0

閱讀[我如何比較中的字符串Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)。 – Manuel

回答

1

錯誤String比較:

if(a1 == q1) 

應該是:

if(a1.equals(q1)) 

同一故事:

if(a3 == q3) 
2

你必須使用他們的比較字符串方法==不比較字符串,而是對象在內存中的位置。 所以,相反的if(a1 == q1)使用if(a1.equals(q1))

編輯:這裏是workig代碼:

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); 
    } 
} 
+0

我試過,但是當我嘗試在cmd中編譯它時,它說29個錯誤 – user2611495

+0

那麼你也需要修復這些錯誤。如果它太多了,通常會有一些}或{在某處丟失。我會看看,並會更新我的答案。 – Matthias

+0

它好吧我固定everythintg謝謝,雖然 – user2611495