我試圖轉換同時while循環和程序甚至編譯,但沒有任何反應。 原始do-while循環代碼:嘗試轉換同時循環到while循環
import java.util.Scanner;
public class CoinFlip
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String coin, again;
int flip, streak = 0;
do
{
flip = 1 + (int)(Math.random()*2);
if (flip == 1)
coin = "HEADS";
else
coin = "TAILS";
System.out.println("You flip a coin and it is... " + coin);
if (flip == 1)
{
streak++;
System.out.println("\tThat's " + streak + " in a row....");
System.out.print("\tWould you like to flip again (y/n)? ");
again = keyboard.next();
}
else
{
streak = 0;
again = "n";
}
} while (again.equals("y"));
System.out.println("Final score: " + streak);
}
}
如何它看起來像後,我試圖做while循環從do-while循環:
import java.util.Scanner;
public class CoinFlip2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String coin, again;
int flip, streak = 0;
again = keyboard.next();
//flip = 1 + (int) (Math.random()*2);
while (again.equals("y"))
{
flip = 1 + (int) (Math.random()*2);
if (flip == 1)
{
coin = "HEADS";
}
else
{
coin = "TAILS";
System.out.println("You flip a coin and it is..." + coin);
}
if (flip == 1)
{
streak++;
System.out.println("\tThat's " + streak + " in a row....");
System.out.print("\tWould you like to flip again (y/n)? ");
//again = keyboard.next();
}
else
{
streak = 0;
again = "n";
}
System.out.println("Final score: " + streak);
}
}
}
代碼編譯沒有問題,但我看到後運行空白輸出它。
DO-while循環保證至少運行一次,而循環都沒有。你得到一個空白的輸出,因爲你正在等待第11行的鍵盤輸入 –
你不能。 'do-while'loops和'while'循環是不可互換的,至少沒有額外的布爾變量。你爲什麼要嘗試? – EJP