2016-03-21 24 views
0

我試圖在用戶的岩石,紙,剪刀選擇(這是作爲r,p或s輸入),但是當我嘗試改變和調用它,它給了我一個錯誤。字符串拒絕聲明,當它已經啓動並分配

這裏是我的代碼:

package labs10; 

import java.util.Scanner; 
import static java.lang.System.*; 

public class RPSRunner 
{ 
    public static void main(String args[]) 
    { 
     Scanner kb = new Scanner(System.in); 
     String full; 
     String response; 
     String player = ""; 

     out.print("Select [R,P,S] :: "); 
     response = kb.next(); 
     if (response.equals("R")) { 
      full = "Rock"; 
     } else if (response.equals("P")) { 
      full = "Paper"; 
     } else if (response.equals("S")) { 
      full = "Scissors"; 
     } 
     out.println("Player chooses " + full); 

     RockPaperScissors game = new RockPaperScissors(); 
     game.setPlayers(response); 
     game.determineWinner(); 
     out.println(game); 
    } 
} 

和我的錯誤是

 
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The local variable full may not have been initialized 
     at labs10.RPSRunner.main(RPSRunner.java:25) 

回答

1
String full; 

您聲明full沒有初始值。如果用戶鍵入RPS,則爲其分配一個值。但是如果他們鍵入其他東西呢?然後full仍然是未初始化的。編譯器不喜歡那樣。

要麼指定它最初的值...

String full = null; 

...或添加最終else條款來處理所有其他用戶輸入。

if (response.equals("R")) { 
    full = "Rock"; 
} else if (response.equals("P")) { 
    full = "Paper"; 
} else if (response.equals("S")) { 
    full = "Scissors"; 
} else { 
    full = null; 
} 
1

好吧,如果response既不是 「R」, 「P」 或 「S」,full不會初始化時您嘗試使用out.println("Player chooses " + full);進行打印。

在這種情況下,您必須爲其分配默認值(或引發異常)。

+0

我試着將它初始化爲String response =「R」; ,那麼用戶可以改變它,但那並沒有解決它。你能否詳細說明一下? – Grant

+0

@Grant如何?只需將'String full;'改爲'String full = null;'就可以消除編譯錯誤。具有「響應」的默認值不會有幫助,因爲稍後使用可能會輸入無效值。這是'full'變量,必須有一個默認值。 – Eran

+0

謝謝,對不起,我一開始不明白! – Grant