字符串变量可能尚未初始化(错误行为到第34行)

我一直试图让字符串初始化,但无济于事。 我已经尝试了所遇到的所有解决方案,我不确定是因为我的无能还是因为我需要一个新的解决方案我已经有了解决方案的逻辑,所以我只需要帮助尝试初始化字符串值。 如果有人可以提供帮助,我会非常感激!

PS诅咒我想要挑战并使用srings。 -_-

import java.util.Scanner; import java.util.Random; public class RockPaperScissors { public static void main (String[] args) { String player, computer; int answer; Scanner scan = new Scanner (System.in); Random generator = new Random(); answer = generator.nextInt(3) + 1; if (answer  3) answer = generator.nextInt(3) + 1; if (answer == 1) computer = "rock"; if (answer == 2) computer = "paper"; if (answer == 3) computer = "scissors"; System.out.println ("Please choose rock, paper, or scissors."); player = scan.nextLine(); if (!player.equalsIgnoreCase("rock") || !player.equalsIgnoreCase("paper") || !player.equalsIgnoreCase("scissors")) { System.out.println ("Please correctly enter one of the three choices: rock, paper, and scissors."); player = scan.nextLine(); } if (player.compareTo(computer) == 0) System.out.println ("It's a draw! You both chose " + player + "!"); if ((computer.equalsIgnoreCase("rock") && player.equalsIgnoreCase("scissors")) && (computer.equalsIgnoreCase("scissors") && player.equalsIgnoreCase("paper")) && (computer.equalsIgnoreCase("paper") && player.equalsIgnoreCase("rock"))) System.out.println ("You lost! The computer chose " + computer + " and you chose " + player + "."); if ((player.equalsIgnoreCase("rock") && computer.equalsIgnoreCase("scissors")) && (player.equalsIgnoreCase("scissors") && computer.equalsIgnoreCase("paper")) && (player.equalsIgnoreCase("paper") && computer.equalsIgnoreCase("rock"))) System.out.println ("You won! CONGRATULATIONS! The computer chose " + computer + " and you chose " + player + "."); } 

}

 String computer; // not initialized 

将此更改为

 String computer = null; or ""// initialized if (player.compareTo(computer) == 0) 

因为,变量计算机将根据条件进行分配。 如果您提到的上述条件不满意。 值为none,因此只显示错误。

编译器看到你有String计算机。 他还可以看到这台计算机已初始化为答案1或2或3.但由于它无法读取逻辑,因此它不知道答案是否可以或不能更低或更高,因此它假设最坏的可能性 – 该计算机不会被初始化。

只需将您的上线更改为

 String computer = ""; 

它应该没问题。

如果我完全理解你的问题,请记住你不能用Java做到这一点:

 String str = "here is some random text"; 

你能做的是

 String str = "here is some " + "random text"; 

换句话说 – 不能在行尾打破字符串,必须关闭它并使用+符号。

您可以通过两种方式初始化Strings的值:

 String abc = "I love basketball"; 

要么

 String abc = new String("I love basketball"); 

你所看到的是一个警告,而不是一个错误。 如果你坚持不在String输入值,那就行了

 String abc = null; 

要么

 String abc = "" 

在后一种情况下,您的String初始化为引用之间的字符。 基本上没什么,但它不是null

为避免潜在的NPE问题,请按如下方式比较String

 "rock".equalsIgnoreCase(playerChoice);