2017-03-15 52 views
0

我知道這是非常基本的Java,但我正在嘗試學習。有人能幫我理解我的錯誤,我該怎麼做來解決它?Java - 將用戶輸入分配給變量並顯示Scoreboard

package com.company; 

import java.util.Scanner; 

public class Main { 

    public static void main(String[] args) { 
     int teamA = 0; 
     int teamB = 0; 


     //asks for the team selection 
     System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B"); 
     Scanner input = new Scanner(System.in); 
     int result = input.nextInt(); 

     public String scoreBoard() { 
      String displayScoreBoard = "No Score"; 
      if (result.toString == "A" || result.toString == "a"){ 
       teamA++; 
       displayScoreBoard = "Score of TeamX is" + teamA; 
      } else if (result.toString == "B" || result.toString == "b"){ 
       teamB++; 
       displayScoreBoard = "Score of TeamY is" + teamB; 
      } System.out.println(displayScoreBoard.toString); 
     } 


     // write your code here 
    } 
} 
+1

不要把'Strings'與'=='用'equals'代替,或者在這種情況下'equalsIgnoreCase'。你的'result.toString()'也不能是「A」或「B」,因爲你期望一個整數。 – Eclipse

+0

非常感謝您的幫助。它解決了我的問題。 :-) –

回答

0

你犯了幾個錯誤。例如,你在一個函數中寫了一個函數。你最好不要那樣做。看看我的代碼。如果您有任何問題,請詢問;)

更新:由於評論應該有一個循環,我已經調整了代碼。

import java.util.Scanner; 
public class Main{ 

    public static void main(String[] args) { 
     int teamA = 0; 
     int teamB = 0; 


     //asks for the team selection 
     while(true) { 
      System.out.println("Would you like to be in Team A or Tema B? Write A for team A and B for team B. Type anything else to quit."); 
      Scanner input = new Scanner(System.in); 
      String result = input.next(); 


      if (result.toUpperCase().equals("A")) { 
       System.out.println("Score of TeamX is" + ++teamA); 
      } else if (result.toUpperCase().equals("B")) { 
       System.out.println("Score of TeamY is" + ++teamB); 
      } 
       else { 
        break; 
       } 

      } 

     } 

} 
+0

非常感謝。明白你的觀點並解決我的問題。爲了更好地理解它,爲了比較兩個字符串,我們需要使用「.equals」。 ==僅適用於int,long或double數據類型,是否正確? –

+0

最好使用equals。看看http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java那裏是非常好的解釋。請提出我的回答(如果您想要,請將其標記爲解決方案)。謝謝 – Markus

+0

我已經標記了你的答案。但不幸的是,由於我的聲望低於15,我無法贊成。我已經稍微更新了這個文件。它工作正常,但每次都從1開始,而不是遞增。我知道我需要一個循環,但不知道在哪裏! –

相關問題