我在编写这个代码时遇到了这个代码的问题,在编译时说
hitOrStick might not have been initialized
我不知道是什么导致它,因为我很确定它已被初始化,如果你能发现任何其他错误,将会非常感激。
(我知道这不是真正的黑杰克,这是非常基本的!)再次感谢。
import java.util.Scanner;
import java.util.Random;
import java.lang.*;
class blackjack
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int total;
boolean play;
int computerTotal = 0;
String hitOrStick;
System.out.println("You are playing BLACK JACK.");
int card1 = (int) Math.ceil(Math.random() * 10);
int card2 = (int) Math.ceil(Math.random() * 10);
total = card1+card2;
System.out.println("Card 1 value: "+ card1);
System.out.println(" ");
System.out.println("Card 2 value: "+ card2);
System.out.println(" ");
System.out.println("You have: " + total);
System.out.println(" ");
if(total == 21)
{
System.out.println("Blackjack! Congratulations you have won!");
}
while(total < 21)
{
System.out.println("Would you like to hit or stick? please type 'H' or 'S'");
System.out.println(" ");
System.out.println("If you type anything other than the options it will count as a STICK.");
hitOrStick = scan.next();
}
if(hitOrStick == "H")
{
int hitCard = (int) Math.ceil(Math.random() * 10);
System.out.println("New Card value: "+ hitCard);
total = total + hitCard;
System.out.println(" ");
System.out.println("You now have: " + total);
if(total > 21)
{
System.out.println("YOU ARE BUST!");
}
}
else
{
System.out.println(" ");
System.out.println("You have chosen to stick.");
System.out.println(" ");
System.out.println("Your total is: " + total);
computerTotal = (int) Math.ceil(Math.random() * 20);
System.out.println(" ");
System.out.println("the computer has: " + computerTotal);
}
if (computerTotal > total)
{
System.out.println(" ");
System.out.println("COMPUTER WINS!");
}
else
{
System.out.println(" ");
System.out.println("YOU WIN!");
}
}
}
答案 0 :(得分:2)
只需声明一个初始值:
String hitOrStick = ""; // or null
编译器不解释您的代码以确保在使用变量时将其设置为值,它只是指出它可能是可能的。
事实上,如果你正在使用Eclipse,你可以设置你的首选项,使得这个编译器错误只是一个警告或被忽略的条件。
答案 1 :(得分:1)
编译器抱怨你的字符串var没有初始值。将var显式为null。
例如
String hitOrStick=null;
答案 2 :(得分:1)
在您的代码中:
int total;
boolean play;
int computerTotal = 0;
String hitOrStick;
已命名了几个变量,但尚未初始化。它有助于将它们全部初始化:
int total = 0;
boolean play = false;
int computerTotal = 0;
String hitOrStick = "";
通过这样做,您可以确保减少错误发生。
你的错误是因为hitOrStick被命名,而不是初始化,然后在代码中,你有if (hitOrStick == "H")
(这不是一个好主意,更好的是if (hitOrStick.equals("H"))
),当hitOrStick是还没有初始化。