Java 'while' loops

overlord20

Gawd
Joined
Feb 5, 2010
Messages
623
Is it possible to use an 'or' statement in a while loop?

Code:
a=0
b=0

while ( a < 5 || b < 5)
{
       if ( user == comp)
       System.out.println("WIN);
       a++;

       if (comp == user)
       System.out.println("WIN);
       b++
}

Once the user or computer wins 5 times then the loop ends. Is that possible? To my knowledge it isn't possible and when I execute it the loop goeas on for ever. When using an 'if' there instead of the 'while' it only runs once. But it will compile and execute.

This is to a much bigger project and I don't want it done for me. Just looking for a little assistance on this one little part. Thank you.
 
Yes, it is possible. Do you have your actual code, because that won't compile, and will end after 5 loops regardless of who wins.
 
I do have my actual code. But it is a school project so I didn't want to break the rules or tempt anyone into breaking them.

Code:
a=0
b=0

while ( a < 5 || b < 5)
{
       if ( user == comp)
       {
           System.out.println("WIN);
           a++;
       }
       else
       System.out.println("you missed");


       if (comp == user)
       {
            System.out.println("Computer WIN);
            b++
       }
       else
       System.out.println("comp missed");
}

if( a == 5)
System.out.println("You Win")
if( b==5)
System.out.println("Comp Win")

Never have done this type of loop where there is an 'or' condition. So this is more similar to my code.. It just keeps looping over and over even when user == comp 10+ times.
 
Last edited:
They are supposed to be the same except one is for the user and one is for the computer..

I got it to work somehow. (Still unsure how). But thanks for the help guys. Really just needed re assurance it was possible. :D
 
haha yeah.. I am terrible at asking for some help :p.. let me show you what I did.

Code:
{
	public static void main(String[] args)
	{
		Scanner scan;
		Random gen;
		
		scan = new Scanner(System.in);
		gen = new Random();
		
		ship_coord(scan, gen);
				
	}	
	
	public static void ship_coord(Scanner scan, Random gen)
	{
		Coord user1, user2, user3, user4, user5;
		Coord comp1, comp2, comp3, comp4, comp5;
		
		user1 = new Coord();
		user2 = new Coord();
		user3 = new Coord();
		user4 = new Coord();
		user5 = new Coord();
		
		comp1 = new Coord();
		comp2 = new Coord();
		comp3 = new Coord();
		comp4 = new Coord();
		comp5 = new Coord();
	// user ship location generation	
		user1.init(scan);
		user2.init(scan);
		user3.init(scan);
		user4.init(scan);
		user5.init(scan);
		
	// computer ship location generation	
		comp1.comp_gen(gen);
	
		comp2.comp_gen(gen);
		 while (comp2 == comp1)
			comp2.comp_gen(gen);
		
		comp3.comp_gen(gen);
		while (comp3 == comp1 || comp3 == comp2)
			comp2.comp_gen(gen);
		
		comp4.comp_gen(gen);
		while (comp4 == comp1 || comp4 == comp2 || comp4 == comp3)
			comp2.comp_gen(gen);
		
		comp5.comp_gen(gen);
		while (comp5 == comp4 || comp5 == comp3 || comp5 == comp2 ||
			comp5 == comp1)
			comp2.comp_gen(gen);
		
		location_guess(scan, gen, user1, user2, user3, user4, user5, comp1,
			comp2, comp3, comp4, comp5);
		
	}
	
	public static void location_guess(Scanner scan, Random gen, Coord user1, 
		Coord user2, Coord user3, Coord user4, Coord user5, Coord comp1, 
		Coord comp2, Coord comp3, Coord comp4, Coord comp5)
	{
		Coord guess, comp_guess;
		int hits, comp_hits;
		
		guess = new Coord();
		comp_guess = new Coord();
		
		
		hits = 0;
		comp_hits = 0;
		
		while (hits < 5 || comp_hits < 5)
		{
		// user guess
			guess.location(scan);
			
			if ( guess.x == comp1.x && guess.y == comp1.y)
			{	
				System.out.println("You Killed a Ship");
				hits += 1;
			}
			else if ( guess.x == comp2.x && guess.y == comp2.y)
			{	
				System.out.println("You Killed a Ship");
				hits += 1;
			}
			else if ( guess.x == comp3.x && guess.y == comp3.y)
			{	
				System.out.println("You Killed a Ship");
				hits += 1;
			}
			else if ( guess.x == comp4.x && guess.y == comp4.y)
			{	
				System.out.println("You Killed a Ship");
				hits += 1;
			}
			else if ( guess.x == comp5.x && guess.y == comp5.y)
			{	
				System.out.println("You Killed a Ship");
				hits += 1;
			}
			else
				System.out.println("Miss, computers turn.");
		
		//Computer Guess
		
			comp_guess.comp_gen(gen);
		
			if (comp_guess.x == user1.x && comp_guess.y == user1.y)
			{
				System.out.println("The computer hit one of your ships");
				comp_hits += 1;
			}
			else if (comp_guess.x == user2.x && comp_guess.y == user2.y)
			{
				System.out.println("The computer hit one of your ships");
				comp_hits += 1;
			}
			else if (comp_guess.x == user3.x && comp_guess.y == user3.y)
			{
				System.out.println("The computer hit one of your ships");
				comp_hits += 1;
			}
			else if (comp_guess.x == user4.x && comp_guess.y == user4.y)
			{
				System.out.println("The computer hit one of your ships");
				comp_hits += 1;
			}
			else if (comp_guess.x == user5.x && comp_guess.y == user5.y)
			{
				System.out.println("The computer hit one of your ships");
				comp_hits += 1;
			}
			else
				System.out.println("Computer missed your ships");
		}
		
		if (hits == 5)
			System.out.println("You killed all the enemy ships! You win!");
		else 
			System.out.println("You lose, the computer wins..");
		
		
	}
}

So basically, the way I explained it was that they were the same when i meant something totally different. Sorry for all the confusion.
 
That code will not work. What happens if you have had 5 hits but the computer has had 0? Step through line by line and answer
 
That is what is throwing me off. If I get 5 hits and the comp has none it will say that I win. If the comp gets 5 hits and I have none it just loops until I get 5 hits.

EDIT: A typo I fixed, broke it. So yes, the loop won't end unless both of the statements are true. I can't for the life of me figure out how to get around it. I thought about making two different loops but then it wouldn't flow right. So I am pondering if a while is the right way to go but I can't see any other possible way to keep it looping until someone wins.
 
Last edited:
Have you considered what makes a while loop work?

If you understand how goto works, then you could visualize a while loop as this:

loopstart:
if (condition is false)
{
goto loopend;
}
do stuff
goto loopstart;

loopend:

that means the loop breaks when the condition is false, right? When is an "or" statement false?
 
Your while loop logic is wrong. Your loop will keep going as long as one of those conditions are true. For example, the computer gets 5 hits so that part is false, but you still have less than 5 hits so the entire expression is true.

Try instead

Code:
if(a == 5 || b == 5) break;

// or this which is logically equivalent

while(a < 5 && b < 5)
 
All you need to do is change the OR to an AND.

That would make it while both are less than 5, loop. If one is equal(or greater) than 5, stop looping.

Have you taken a Finite/Discrete Math yet? Either way you need to freshen up or take some time to learn boolean logic. It will help you to recognize when to use or's and and's.
 
I haven't had the opportunity to take discrete math yet.. thanks guys. I was losing it last night and this helped out a lot.. The switching to the and statement was perfect. I for some reason was thinking it was more complicated then that, and therefore was over thinking the entire situation.
 
Last edited:
Your while loop logic is wrong. Your loop will keep going as long as one of those conditions are true. For example, the computer gets 5 hits so that part is false, but you still have less than 5 hits so the entire expression is true.

Try instead

Code:
if(a == 5 || b == 5) break;

// or this which is logically equivalent

while(a < 5 && b < 5)
1) Try to let him find the solution through help, not answers
2) Those are not logically equivalent. Perhaps effectively so for most code, but certainly not for all, and should not be presented as such
 
Came up with another problem. Apparently my location while loops were bonk. (After like 15 games I started getting to ships on one spot). I am trying to use arrays through methods so they can check and make sure that the random numbers aren't the same. Arrays have been the hardest part for me over the 2 semesters so far I have been in java (Java 1 and 2). Does this look right to you?

Code:

Then the method:
Code:

Alls it returns is this:



I would ask my instructor but its 11:30 and he is most likely asleep. I don't want the answer laid out for me, I just need a little help arriving there. I don't recall running into this issue before. I am going to read some text and google it as well.

Edit: Just read in my text book that java can't print arrays by itself, so I need to figure out how to do that. Now that I think about it, I remember my instructor saying this when we first started arrays.

I deleted the last code I posted as I made some headway after reading a bit. The only thing now is I have to make sure that x,y combo doesn't repeat.

Code:
{
		Coord user1, user2, user3, user4, user5;
		Coord comp1, comp2, comp3, comp4, comp5;
		int[] x, y;
		
		x = new int[1];
		y = new int[1];
		
		
		user1 = new Coord();
		user2 = new Coord();
		user3 = new Coord();
		user4 = new Coord();
		user5 = new Coord();
		
		comp1 = new Coord();
		comp2 = new Coord();
		comp3 = new Coord();
		comp4 = new Coord();
		comp5 = new Coord();
	// user ship location generation	
	//	user1.init(scan);
	//	user2.init(scan);
	//	user3.init(scan);
	//	user4.init(scan);
		user5.init(scan);
		
	// computer ship location generation	
		comp1.comp_gen(gen, x, y);
		comp2.comp_gen(gen, x, y);
		comp3.comp_gen(gen, x, y);
		comp4.comp_gen(gen, x, y);
		comp5.comp_gen(gen, x, y);
		
		location_guess(scan, gen, user1, user2, user3, user4, user5, comp1,
			comp2, comp3, comp4, comp5);
		
	}

The Method:
Code:
public void comp_gen(Random gen, int[] x, int[] y)
	{
		int i;
		
		for ( i = 0; i < 1; i++)
		{
			x[i] = Math.abs(gen.nextInt()) % (5-1+1) + 1;
			System.out.print("Computer: " + x[i] + ",");
		}
		for ( i = 0; i < 1; i++)
		{
			y[i] = Math.abs(gen.nextInt()) % (5-1+1) + 1;
			System.out.println(y[i] + " ");
		}
	}

The random x and y now shows, but I am still getting x and y duplicates.
 
Last edited:
A few things just at a glance.

I can't tell why you are using arrays for x,y instead of just integers.
I'm not sure why the for loops either, as they are never executed more than once.
Why % (5-1+1)? Java will treat that as % 5, no?

Are you getting repeats every time or just randomly? When you are % 5 + 1 the random number, which is positive because of the absolute value, The % 5 makes it so the values will always be either 0, 1, 2, 3, 4, then your + 1 would translate those values to 1, 2, 3, 4, 5. You only have five choices for the values. Just by random chance you will get the same coordinates. If you wanted to make sure they aren't putting one on a coord that has already been generated you would need to store previous values and check for that.

It doesn't look like you are setting the coordinates for the comps either. You are generating the values and setting them to x[0], y[0], and printing them, but the values aren't getting stored into the coords. Unless it is something you omitted. If you are later calling the coords by x[0], y[0], they are going to be whatever x[0], y[0] were last assigned. This could also explain why they are all at the same coordinate. You want something like setX(), getX(), setY(), getY() in your coord class and assign the values you generated to the objects.

It looks like a lot of code is missing. I know you did it to simplify what we are looking at, but it also makes us have to guess and/or assume about the rest of the implementation.
 
Well, I was just trying to do what my instructor said. "You will need to use an array so you don't get repeats of the same coordinates".

So I was trying that as my previous methods of guessing didn't work. Once I can figure this last section out it will help with the very last part. I will look at it more, and if I find something out or find something that will work I will post. I will also look farther into what you have said Nightrainsrt4.
 
Well, I was just trying to do what my instructor said. "You will need to use an array so you don't get repeats of the same coordinates".
Think about what kind of array you need. How would you check that a new coordinate set doesn't overlap an existing one? Take a piece of graph paper, draw a square, and start coloring in. Follow your programs logic while doing so, and see where things break down.
 
Please don't edit your posts except to eliminate typos. Doing so makes it confusing to people what you are looking for help with.
 
I wrote it all out on paper. I need to figure out a way for x[0] and y[0] to be stored in comp1.

So I have 2 array's with 5 slots (0-4), and random numbers are generated filling 0-4 slots. I need to store x[0] and y[0] in comp1, then I need to see if x[1] and y[1] match the previous array slots and if they don't then x[1] and y[1] are stored in comp2 and so on through array slot 4.

So first of all, I need to figure out how to store the 0 slot (and the rest) into comp1 (and various comp's).

Sorry Whatsisname... Didn't want to confuse everyone with tons of different code posts.
 
Arrays can be of any type. Have you considered what kind of array to make, rather than having an x[] and y[]?

Or, another way to think about it, what would you do if I asked you to store 100 sets of coordinates? 1000? Are you going to type "coord1, coord2, ... coord100" and so on?
 
Thinking I should use a 2 dimensional array? My instructor said something about bring over another parameter from the function to the method..

Arrays are officially kicking my ass.
 
Last edited:
Thinking I should use a 2 dimensional array? My instructor said something about bring over another parameter from the function to the method..

Arrays are officially kicking my ass.

I thought the second thing I said would be the obvious hint. Let me give you an example.

Code:
class Foo
{
public int bar,baz;
public Foo(int bar, int baz)
{
this.bar = bar;
this.baz = baz;
}
}

void LotsOfFoo(int howMuchFoo)
{
   Foo[] foos = new Foo[howMuchFoo];
   for (int i = 0; i < foos.length; i++)
   {
      foos[i] = new Foo(i,i+1);
      Foo curFoo = foos[i];
      System.out.println("Foo " + i + " has bar=" + curFoo.bar + " and baz = " + curFoo.baz);
   }
}

With that, you can see some of the basics for arrays: initialization of an array in a loop, accessing a particular array element, etc. How can you apply that to your need to keep track of coordinates?
 
Well, I got the array to work and even though I had to use ints to do it, it actually reduced the main file drastically.

The only thing now is finding a way to check if the new random number is already in the array. Which I have no clue. I have been reading a lot the past few days and I think I am just having a hard time comprehending what everyone is telling me and what I am reading and I don't even know why. (This hasn't been hard for me to pick up at all except for arrays).

I was thinking a simple 'if' statement could work, but then I don't know how I would set it up.

Also want to thank everyone that has posted for the help as I struggle though this :D.

foos = new Foo(i,i+1)



what is the "i+1" for?
 
Last edited:
That's just there so I have different numbers in each...


When you say "had to use ints", do you mean an array of ints, or copying/pasting/changing the variable name?

Have you considered a way you could check the array for duplicate entries?
 
Tawnos is definitely showing you the right path. You want to be using an object oriented approach, with coordinates storing the xy data and your array storing the coordinates.

When you generate a random number think about comparing that to all the xy values in the coordinates you already have. You should be iterating through a loop.

When you first initialize an array you need to make it big enough to store all the data you are going to need. Think of an array like a container with individual compartments. When you build this container you need to build as many compartments as you need as there is no direct way to add more once it is built. So instead of using an array of size 1, think about how many different coordinates you need to store and make it that big. If you do not know you can try to make an educated guess as to how big you are going to need, but remember java will assign memory to the entire array, to each "container", whether it is empty or not.

But seriously take a strong look through Tawnos piece of code. Think about what a coordinate is and what pieces of information a coordinate needs to have while you do so. You won't be able to directly paste any of that code so don't try and just plug it in, but instead really look through it until you know what it means. Write it out on paper if you have to; it might help you understand the process better. Don't let yourself get confused by the foo, bar, baz naming. Everything you need is there you just have to let yourself see it.
 
I got the program done and turned in. But I am still going to really look at the code. (Have it on the white board right now. So thanks guys. Definitely coming back here for help.
 
Back
Top