我尝试将do-while转换为while循环,程序甚至编译,但没有任何反应。 原始的do-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 );
}
}
尝试从do-while循环执行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);
}
}
}
代码编译没有问题,但运行后我看到空白输出。
答案 0 :(得分:2)
这是因为您从未将again
变量初始化为y
,因此它永远不会匹配条件才能输入while
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String coin, again = "y";
int flip, streak = 0;
// 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();
// again = keyboard.next();
} else {
streak = 0;
again = "n";
}
}
System.out.println("Final score: " + streak);
keyboard.close();
}
输出:
That's 1 in a row....
Would you like to flip again (y/n)? y
You flip a coin and it is...TAILS
Final score: 0
答案 1 :(得分:1)
使用again
初始化您的"y"
:
String coin, again;
int flip, streak = 0;
again = "y";
...
并在while循环中询问键盘输入:
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();
}