How to stop the loop-java - java

I need to check if a 2d array is full and if it is a latin square. I have two methods to check for both conditions but when I put the check in the do while loop it doesn't check. I want the game to stop if the board is full then proceed to check if it is a latin square. I set it up to where it checks for an empty element in the array. This is the code for the fullboard check.
public static boolean fullBoard(char [][] square){
for(int i = 0; i < square.length; i++){
for(int j = 0; j < square.length; j++){
if(square[i][j] == 0) {
return false;
}
}
}
return true;
}
This is the code for the do while:
do {
promptUser(square);
printBoard(square);
if(fullBoard(square)) {
isLatinSquare(square);
}
}while(isLatinSquare(square));
System.out.println("you win");
printBoard(square);
}

Ok I am not sure to understand everything but I will try to help.
When I look at your do while, I can see that the
if(fullBoard(square)) {
isLatinSquare(square);
is useless. The method isLatinSquare returns a bool. You don't even use it's returned value.
If you want the game to end when until the game is full and the scare is latin:
do {
promptUser(square);
printBoard(square);
}
while(isLatinSquare(square) && fullBoard(square));
System.out.println("you win");
printBoard(square);
}
if you want to stop the game temporarly when it is full:
do {
promptUser(square);
printBoard(square);
if(fullBoard(square)) {
Thread.sleep(2000); //2 sec pause
}
}
while(isLatinSquare(square));
System.out.println("you win");
printBoard(square);

can you please try it this way
do {
promptUser(square);
printBoard(square);
}while(!fullBoard(square));
if(isLatinSquare(square)) {
System.out.println("you win");
}
else {
System.out.println("you lose");
}
printBoard(square);

Related

If statement within if statement is not running

So i am trying to make a text based rpg game and what is supposed to happen here is when you activate a hunt by typing hunt it asks you yes or no. However even when i input yes, the you killed the boar message does not pop up. I am fairly new to java so sorry if the code is bad.
//Branches
if (ins.equals("branches") && loc.equals("forest")) {
System.out.println("You got a branch");
ib++;
} else if (ins.equals("branches") && !"forest".equals(loc)) {
System.out.println("You need to be in the forest to cut branches");
} else if (ins.equals("bcount")) {
System.out.println(ib);
}
//Branches
//Stones
if (ins.equals("stones") && loc.equals("mountains")) {
System.out.println("You got a stone");
is++;
} else if (ins.equals("stones") && !"mountains".equals(loc)) {
System.out.println("You need to be in the mountains to gather stones");
} else if (ins.equals("scount")) {
System.out.println(is);
}
//Stones
//Spears
if (ins.equals("spear") && is >= 1 && ib >= 1) {
System.out.println("+1 spear");
is--;
ib--;
ispear++;
} else if (ins.equals("spear") && is < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spear") && ib < 1) {
System.out.println("Insufficient resources");
} else if (ins.equals("spearcount")) {
System.out.println(ispear);
}
//Spears
//Hunt
if (ins.equals("hunt") && ispear >= 1) {
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes")) {
System.out.println("You killed the boar!");
}
} else if (ins.equals("hunt") && ispear < 1) {
System.out.println("You dont have any spears");
}
}
If the while loop at the top controls the input then it is not possible for the code to get back to that inner if statements because ins cannot equal both "hunt" and "yes" at the same time. You need to do what #Spectric suggested in the comments and read the input again, or you need to use another way.
In the example below, we have used a boolean as a flag Boolean hunting = false;, and an OR condition || to allow us to get back inside the hunting section if (huting == true || ins.equals("hunt")....) then finally we need to make sure we trigger the flag on/off when hunting starts/ends like this hunting = true; or hunting = false;
Then all put together:
//Flag that allows us to trigger hunting
//This needs to be placed outside of the while loop
Boolean hunting = false;
//While loop that gets input and prints the next instruction
while (ins != null)
{
//Your code here to get the input
//...
//ins = scanner.nextLine();
//...
//Hunt
//add an or "||" condition so that if the hunting flag is true then we can get back inside this if statement:
if (hunting == true || ins.equals("hunt") && ispear >= 1)
{
//Set the hunting flag to true, so that we can get back to here in the next loop:
hunting = true;
System.out.println("A wild boar comes charging at you! Throw spear? (yes or no)");
if (ins.equals("yes"))
{
System.out.println("You killed the boar!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
//Make sure you have an else statement to set the hunting flag back to false
else
{
System.out.println("The boar ran away!");
//Reset the hunting flag so future commands don't break:
hunting = false;
}
}
else if (ins.equals("hunt") && ispear < 1)
{
System.out.println("You dont have any spears");
}
}

How to change while(true)

This is code for my Tic Tac Toe game. My professor doesn't want us to use while(true) and breaks. I don't know how to change it. Can someone please help me.
public void playerMakeMove()
{
while(true)
{
System.out.println("It is "+username+"'s move");
System.out.println("Give me your best move!");
int move = input.nextInt();
if (validatePlayerMove(move))
{
if (checkPositionAvailability(move))
{
board[move] = 'H'; //'H' for player move
break;
}
else
{
System.out.println("Position not available.\nMake a different choice.");
continue;
}
}
if (move >= 9 || move <= -1)
{
System.out.println("Invalid entry!");
continue;
}
I highly recommend using a boolean that does the job instead of while (true) { code }
Useful link for this : Are "while(true)" loops so bad?
You could write something like this:
while ( gameInLimbo() ) {
makeAnotherMove();
}
where gameInLimbo() is a method that returns true if there is no current winner and there are still open square(s), and false otherwise.

Boolean loop wont set false

i have loops in all my other applications, but this just wont seem to work.
public void loanBook() {
boolean loop3 = true;
System.out.println("So you wanna loan a book? Excellent choice.");
while (loop3) {
for (int i=0; i<books.size(); i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book) == true) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size(); j++) {
if (customers.get(j).getSignedIn() == true) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
----> loop3 = false; doesnt work for some reason
}
}
}
}
}
System.out.println("Couldnt find book");
}
}
It keeps repeating the loop3 even though i set it to false. It should go back to the main menu afterwards, but it wont.
I tried to isolate the problem, and no problem. I've been looking at the code for an hour now and i cant seem to find any problem. Anybody got a clue?
the isolated problem that worked:
public void loanBook() {
boolean loop = true;
while (loop) {
System.out.println("lol");
-----> loop = false; works fine
}
System.out.println("lol");
}
my System out prints work just fine so i know it gets through my loops correctly.
You have 3 nested loops. The other loop (the while loop) terminates when loop3 becomes false.
However, you are setting loop3 to false deep within the inner most loop, which means the while loop won't check the value of loop3 until the 2 inner for loops finish.
If you want to break from all the loops, you'll need some break statements and or additional conditions. For example:
while (loop3) {
for (int i=0; i<books.size() && loop3; i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book)) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size() && loop3; j++) {
if (customers.get(j).getSignedIn()) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
loop3 = false;
}
}
}
}
}
System.out.println("Couldnt find book");
}
This will leave both inner loops when loop3 becomes false, which will allow the outer loop to terminate immediately.
You want to break out of the while loop as soon as you set it to false. You could do that with labels
public void loanBook() {
boolean loop3 = true;
System.out.println("So you wanna loan a book? Excellent choice.");
while (loop3) {
outerloop: // added
for (int i=0; i<books.size(); i++) {
System.out.println("Search for the book you're looking for: ");
String book = in.nextLine();
if (books.get(i).toString().contains(book) == true) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.next();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size(); j++) {
if (customers.get(j).getSignedIn() == true) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
loop3 = false;
break outerloop; // added
}
}
}
}
}
System.out.println("Couldnt find book");
}
}

Method to check whether a number is prime or composite

public boolean isPrimeNum (int n) {
boolean isPrime= true;
for( int i=2; i<= n; i++) {
if( n%i==0) {
isPrime= false;
}
isitPrime= true;
if(isPrime)
System.out.println("its a prime number");
else
System.out.println("its a composite number"); }
}
I have attempted to write this method to check whether a number is prime or composite, but I am not sure whether it is correct. Any kind of help would be appreciated and thanks in advance.
Here is your refactored code. Feel free to comment if you are having questions.
class PrimeChecker { //Has to be in a class
public boolean isPrimeNum(int n) {
boolean isPrime=true;
for (int i=2; i < n; i++) { //Has to be i < n instead of i <= n, every number can be divided by itself
if (n%i==0) {
isPrime=false;
break; //Note you can break then
}
} //You were missing this
//Removed : isitPrime= true; makes absolutely no sense
if(isPrime) {
System.out.println("its a prime number");
return true; //Breaks, you wont need else anymore
} //You were missing these again
System.out.println("its a composite number");
return false;
}
}
You can make it a bit (very slight) more efficient by checking the modulo(%) till <=(n/2) as a number's biggest factor (excluding itself) will always be less than or equal to its half, ie, for(int i=2;i<=n/2;i++);
Oh and check for 2 and 3 separately:)
You should google search for this type of questions.
However I am answering an optimized way of finding prime numbers
private static boolean isPrimeNum(int n){
if(n==2 || n==3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i<=Math.sqrt(n);i=i+2){
if(n%i==0) return false;
}
return true;
}

Skipped nextLine()

I'm trying to make a short game where the player has to open a treasure chest and buy stuff from a shop, but when i exit the shop, it tells me "Invalid command. Use "shop" or "open."" I added the "end of loop" and found out that after store is finished, it ends the loop and ignores the nextLine() command and goes directly to the if-else ladder. Can anyone help me solve this?
while (win == 0)
{
opt = s.nextLine();
er = 1;
if (opt.equalsIgnoreCase("shop"))
{
store();
er = 0;
}
else if (opt.equalsIgnoreCase("open"))
{
gold += open();
}
else if (opt.equalsIgnoreCase("exit"))
{
return;
}
else if (er == 1)
{
System.out.println("Invalid command. Use \"Shop\" or \"Open.\"");
wait (1);
}
if (gold >= 1000000)
{
win = 1;
}
System.out.println ("End of loop");

Categories