我試圖在用戶的岩石,紙,剪刀選擇(這是作爲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)
我試着將它初始化爲String response =「R」; ,那麼用戶可以改變它,但那並沒有解決它。你能否詳細說明一下? – Grant
@Grant如何?只需將'String full;'改爲'String full = null;'就可以消除編譯錯誤。具有「響應」的默認值不會有幫助,因爲稍後使用可能會輸入無效值。這是'full'變量,必須有一個默認值。 – Eran
謝謝,對不起,我一開始不明白! – Grant