Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loops 1

Status
Not open for further replies.

heather473

Technical User
Dec 2, 2000
8
0
0
US
Can someone please explain the loop process to me so I can figure out why the loop isn't working in my program.
Thanks
import cs1.Keyboard;

public class Slots2
{
//-----------------------------------------------------------------
// Plays a Slot Machine game with the user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MAX = 9;
int Num1, Num2, Num3;
String another = ("n");

System.out.print (" Would you like to play");
another = Keyboard.readString();

{
while (another == ("n"));
Num1 = (int) (Math.random() * MAX) + 1;
Num2 = (int) (Math.random() * MAX) + 1;
Num3 = (int) (Math.random() * MAX) + 1;

System.out.print (Num1);
System.out.print (Num2);
System.out.println (Num3);
{
if (Num1==Num2)
if (Num2==Num3)

System.out.println ("You win!");
else
System.out.println ("Sorry, You Lose.");
else
System.out.println ("Sorry, You Lost.");

System.out.println ("Would you like to play again(y/n)?");
another = Keyboard.readString();
}
}
{
System.out.println ("Thank you, Have a good day!");
}
}
}
 
Ok...:)
I think that the solution to your problem is undertanding
that for String comparation you must use the equals
or equalsIgoneCase methods defined in the class String...

Your loop condition actually compares references to object
not the content of the String object,
you'd rather substitute it for
Code:
while ( another.equals( "n" ) )
 
Besides
The beginblock and ending block of if and loop statement are in a wrong place...
The right place is
Code:
while( boolean_expression ) {
  // statements excecuted when the condition is true
}

if( boolean_expression  ) {
  // statements excecuted when the condition is true
}

if( boolean_expression  ) {
  // statements excecuted when the condition is true
}
else {
  // statements excecuted when the condition is false
}

look out statements like this...
Code:
while ( expr ) ; // <-- this ; signals that the loop 
                //  <-- ends right here
{
  // Therefore this block is not part of the loop 
  // because of ;
}
the same for if statements .
Code:
if ( expr ) ; // <-- this ; signals that the if statment
              //  <-- ends right here
{
  // Therefore this block is not part of the statement
  // because of ;
}
 
Thank you soo much, I understand better now.
heather
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top