[英]Can you help me identify the error in this code? I dont seem to understand why it isn't working?
[英]Dont understand why my method isn't working?
public class BlackJackRules
{
Random generator = new Random();
int c = 0;
String card1;
/* Creates a random number which turns into
* a string card(card1).
*/
public String getCard()
{
c = generator.nextInt()+14;
if(c == 1)
card1 = "Ace";
else if(c == 2)
card1 = "Two";
else if(c == 3)
card1 = "Three";
else if(c == 4)
card1 = "Four";
else if(c == 5)
card1 = "Five";
else if(c == 6)
card1 = "Six";
else if(c == 7)
card1 = "Seven";
else if(c == 8)
card1 = "Eight";
else if(c == 9)
card1 = "Nine";
else if(c == 10)
card1 = "Ten";
else if(c == 11)
card1 = "Jack";
else if(c == 12)
card1 = "Queen";
else if(c == 13)
card1 = "King";
return card1;
}
}
這是驅動程序。
public class BlackJack
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String userStart = new String();
String userQuit = new String();
String card1 = new String();
System.out.println("Would you like to play some BlackJack?");
userStart = scan.next();
if(userStart.equalsIgnoreCase("yes"))
{
System.out.println("Here we go...");
while(userQuit.equalsIgnoreCase("yes"))
{
System.out.println("Your first card is a " + card1.getCard());
}
}
else
System.out.println("Okay.");
}
}
}
我只是想不通...我嘗試重新排列我的代碼。 我是剛上高中的AP課程的新手,並且在方法的概念中掙扎。 謝謝你的幫助!
您尚未創建BlackJackRules的實例
這個
String card1 = new String();
應該
BlackJackRules card1 = new BlackJackRules();
這樣就可以了
System.out.println("Your first card is a " + card1.getCard());
由於getCard()
在BlackJackRules
類中,因此您首先需要創建一個實例來使用其方法
同樣在您的方法中,您只想使用此
c = generator.nextInt(13) + 1
代替
c = generator.nextInt()+14;
你可能想要。
c = generator.nextInt(13) +1;
所編寫的代碼即使編譯並運行,也極有可能不會產生預期的結果,因為您將在32位整數的整個范圍內生成整數。
除了以前的答案:
在第二點上,最好將循環更改為“ do-while”,並添加提示,詢問用戶是否要畫另一張牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.