[英]Java while loop never enters loop
我正在用Java編寫視頻撲克,我需要問玩家是否要從他們的手中取出任何卡。 我為此編寫了一個while
循環,但它現在無法按預期的方式工作。 如果有人可以向正確的方向發送郵件,我將不勝感激-我對Java還是陌生的。 ( counter
在那里,所以玩家最多只能取出5張卡)
String response = "y";
int counter = 0;
System.out.println("Remove any cards?");
System.out.println("Enter y for 'yes' and n for 'no'");
response = input.nextLine();
while((response != "n") && (counter < 5))
{
System.out.println("Enter the number of a card to be removed (1-5)");
int l = input.nextInt();
p.removeCard(p.getHand().get(l-1));
p.addCard(cards.deal());
cards.incrementTop();
counter ++;
System.out.println("Card removed. More? Type 'yes' or 'no'");
String answer = input.nextLine();
if (answer == "no")
{
response = "n";
}
}
您不能使用!=
或==
比較字符串。
while(!("n".equals(response)) && (counter < 5))
這里也一樣
if (answer == "no")
其他需要改進的地方
.equalsIgnoreCase()
) 給您的另一個提示:將布爾變量用於yes/no
,更好,更容易:)
嘗試使用String.equals()方法比較字符串。 你的while循環應該是
while(( !response.equals( "n" )) && (counter < 5))
{
//do Something
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.