How to change while(true) - java

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.

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");
}
}

Java: Rock Paper Scissors game loop

I'm trying to get this loop to work, but can't get it figured out, tried a few different kinds and haven't had any luck, gone back through some of my studying and poked around to try to get some insight but haven't been able to successfully get it to work. the base program code is as follow, basically this was a project i did a few weeks ago, and a new project wants us to go back in and have it so the game continuously plays until the user inputs a "3". I can't figure it out, I can't seem to find any examples or help online. I'm not looking for someone to just give an answer, just looking for a nudge in the right direction.
TL;DR: the game should repeat until the user inputs 3
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("scissor (0), rock (1), paper (2): ");
int user = input.nextInt();
int computer = (int) (Math.random() * 3);
System.out.print("The Computer is ");
switch (computer) {
case 0:
System.out.print("scissor. ");
break;
case 1:
System.out.print("rock. ");
break;
case 2:
System.out.print("paper. ");
}
System.out.print(" You are ");
switch (user) {
case 0:
System.out.print("scissor");
break;
case 1:
System.out.print("rock");
break;
case 2:
System.out.print("paper");
}
if (computer == user) {
System.out.println(" too. It is a draw");
} else {
boolean win = (user == 0 && computer == 2)
|| (user == 1 && computer == 0)
|| (user == 2 && computer == 1);
if (win) {
System.out.println(". You won!");
} else {
System.out.println(". You lose!");
}
}
}
}
You can put all your code in your main method into an infinite loop and exit the program when the user inputs 3 like this.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) { //start of the loop
Scanner input = new Scanner(System.in);
//setting the variable to an incorrect value,
//so the text is printed always at least once
int user = -1;
//while the input is incorrect (lower than 0 or higher than 3)
while(user < 0 || user > 3) {
//ask for the input
System.out.print("scissor (0), rock (1), paper (2), exit (3): ");
//try reading an integer, as the user might input whatever (String, float,..)
try {
user = input.nextInt(); //trying to read an integer
} catch (Exception e) { //in case of an invalid input (not an integer)
//I still want to "read" the tokens,
//because the .nextInt() did not process the input
input.next();
}
if (user == 3) System.exit(0);
}
//rest of your code
} //end of the loop
}
You can see, that I used try and catch to check for other inputs than an integer. I also repeat asking for the input until it is valid. You might not necessarily need that if it is not part of your focus right now and exchange it just for the following.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
while(true) { //start of the loop, loops forever unless the user inputs 3
Scanner input = new Scanner(System.in);
System.out.print("scissor (0), rock (1), paper (2): ");
int user = input.nextInt(); //trying to read an integer
if (user == 3) System.exit(0); //if the input is 3, exit the program
//rest of your code
} //end of the loop
}
Your code has no loops at all, though.
You can use the while construct, or the do/while construct, which is quite similar:
boolean playing = true;
while (playing) {
... all the code you currently have ....
}
would keep looping; until you set playing to false, of course, which you can do when the user enters 3.

How to stop the loop-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);

Is the following flowchart correct for the given code?

I have designed a flowchart that is based on this code in Java.
public static void main(String args[]) throws IOException {
BufferedReader bw = new BufferedReader(new InputStreamReader(System.in));
attendance_and_student_management object = new attendance_and_student_management();
int flag = 1;
do {
{
int var = object.menu();
if (var == 1) {
System.out.println("\f");
object.add_student();
System.out.println();
} else if (var == 2) {
System.out.println("\f");
object.search_student();
System.out.println();
} else if (var == 3) {
System.out.println("\f");
object.change_student_information();
System.out.println();
} else if (var == 4) {
System.out.println("\f");
object.take_attendance();
System.out.println();
} else if (var == 5) {
System.out.println("\f");
object.attendance_summary();
System.out.println();
} else if (var == 6) {
System.out.println("\f");
object.monthly_defaulter_list();
System.out.println();
} else if (var == 7) {
System.out.println("\f");
System.out.println("THANK YOU FOR USING THE PROGRAM!!");
System.exit(0);
} else {
System.out.println("\f");
System.out.println();
System.out.println("Invalid Input. Would you like to try again? Press 1 for Yes");
int choice1 = Integer.parseInt(bw.readLine());
if (choice1 == 1) {
continue;
} else {
break;
}
}
System.out.println("Would you like to return to the Main Menu to perform more tasks? Press 1 for Yes and 0 for No");
flag = Integer.parseInt(bw.readLine());
if (flag != 1) {
System.out.println("Are you sure you want to exit? Press 1 for Yes");
int flag2 = Integer.parseInt(bw.readLine());
if (flag2 == 1)
flag = 0;
else
flag = 1;
}
}
}
while (flag == 1);
}
The flowchart is given below:
I am still learning how to construct flowcharts, therefore, I am not sure whether this diagram is correct. Any inputs or suggestions will be much appreciated.
PS: I tried to make the flow chart a bit simpler, please do tell if this is more appropriate than the previous one...
Your condition on the chart
Is var equal to 1,2,3,4,5,6 or 7?
ist not 100% right.
Your program works with if and else if conditions, which check each condition serial. You first check the 1, then the 2, then the 3 and so one...
Your chart shows this conditions as an All-In-One condition, what in java mean a switch).
So your chart should show these if's more like this:
Next, you dont need to draw the chart-boxes
Execute Method
In your code, you can draw just one box for the action in a true if-condition (like my added image).
And finally, you should have only one "Exit / End" point on the chart. Each flow that stopps the program, should link to this End-Point.

Where should I put a Scanner.close();?

i need to know where i should put a Scanner close in this code to stop resource leak.
public class guess_main {
public static void main(String[] args) {
Random numGenerated = new Random();
int numToGuess = numGenerated.nextInt(100);
int numTries =0;
int Guess;
boolean win = false;
Scanner inputNum = new Scanner(System.in);
while (win == false){
System.out.println("Please guess a number between 1 and 100");
Guess = inputNum.nextInt();
numTries++;
if (Guess == numToGuess){
win = true;
}
else if (Guess < numToGuess) {
System.out.println("Your guess is LOW!");
}
else if (Guess > numToGuess){
System.out.println("Your guess is HIGH!");
}
}//End of loop
System.out.println("You won in " + numTries + " goes. Well done!");
}
}
Add it at the end of the loop.
Things should be closed as soon as you are done using them.
If you do anything else with the scanner afterwords, you will need to move it. For example, if you rewrite it to offer the option for another game, you will need to place the closing statement after your confirm that they don't want to play.
You should put it after the end of your loop:
while (win == false) {
...Game logic...
}
inputNum.close();
What this does is close the input stream, so you don't have memory leaks.
In addition to that, please follow Java coding conventions. The only (non-indent related) breaches I saw was that Guess is capitalized, but it's an object, and guess_main should be GuessMain (Uppercase and using camelCase instead of underscores) but it's good to keep an eye out, just in case.
Addendum: As David Wallace pointed out, there is a method that might throw an exception. If you don't care, then the above solution will work, but if you do, this is better:
try (Scanner inputNum = new Scanner(System.in)) {
...Game logic...
} catch (InputMismatchException e) {
e.printStackTrace();
}

Categories