我有這個代碼的問題其對一所學校的任務,編譯時它說變量hitOrStick可能尚未初始化
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!");
}
}
}
將顯式空值置於您的var。例如String hitOrStick = null; – user1697575