I trying convert do-while to while loop and program even compile, but nothing happens. Original do-while loop code:
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 );
}
}
How it looks like after I trying to do while loop from do-while loop:
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);
}
}
}
Code compile without problem but I see blank output after running it.
do-whileloops andwhileloops are non-interchangeable, at least without an extra Boolean variable. Why are you even trying?