我一直试图让字符串初始化,但无济于事。我已经尝试了所遇到的所有解决方案,我不确定是因为我的无能还是因为我需要一个新的解决方案我已经解决了程序的逻辑,所以我只需要帮助尝试初始化字符串值。如果有人可以提供帮助,我会非常感激!
P.S诅咒我想要挑战并使用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 < 1 || 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 + ".");
}
}
答案 0 :(得分:1)
String computer; // not initialized
将此更改为
String computer = null; or ""// initialized
if (player.compareTo(computer) == 0)
因为,变量计算机将根据条件进行分配。如果您提到的上述条件不满意。值为none,因此只显示错误。
答案 1 :(得分:1)
编译器看到你有String计算机。他还可以看到这台计算机已初始化为答案1或2或3.但由于它无法读取逻辑,因此它不知道答案是否可以或不能更低或更高,因此它假设最坏的可能性 - 该计算机不会被初始化。
只需将您的上线更改为
String computer = "";
它应该没问题。
答案 2 :(得分:0)
如果我完全理解你的问题,请记住你不能用Java做到这一点:
String str = "here is some
random text";
你能做的是
String str = "here is some " +
"random text";
换句话说 - 不能在行尾打破字符串,必须关闭它并使用+
符号。
答案 3 :(得分:0)
您可以通过两种方式初始化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);