Java: Rock Paper Scissors game loop - java

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.

Related

Using break in while loop is giving me error "break cannot be used outside of a loop or a switch" even though it is already inside a loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
public class rps {
public static void main(String args[]) {
int userCount = 0;
int myCount = 0;
int tieCount = 0; /* All 3 are counters that keep track of win scores */
Scanner scan = new Scanner(System.in); /* Create a scanner */
String play = ""; /* Scanner string local variable */
do {
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine(); //
}
while (play.equalsIgnoreCase("play")); {
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
String rps = scan.nextLine();
while (rps.equals('R') || rps.equals('P') || rps.equals('S')) {
System.out.println("You chose: " + rps);
}
int rand = (int)(Math.random() * 3);
String myMove = "";
if(rand == 0) {
myMove = "Rock";
}
else if(rand == 1) {
myMove = "Paper";
}
else {
myMove = "Scissors";
}
System.out.println("I chose: " + myMove);
if(rps.equals(myMove)) {
System.out.println("Tie!");
tieCount++;
}
else if(rps.equals('P') && myMove.equals('S')) {
System.out.println("Scissors beats paper, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals('R')) {
System.out.println("Rock beats scissors, a win for me!");
myCount++;
}
else if(rps.equals('R') && myMove.equals('P')) {
System.out.println("Paper beats rock, a win for me!");
myCount++;
}
else if(rps.equals('S') && myMove.equals('P')) {
System.out.println("Scissors beats paper, a win for you!");
userCount++;
}
else if(rps.equals('R') && myMove.equals('S')) {
System.out.println("Rock beats scissors, a win for you!");
userCount++;
}
else if(rps.equals('S') && myMove.equals('P')) {
System.out.println("Paper beats rock, a win for you!");
userCount++;
}
System.out.println("Please enter Play if you want to play the game again or anything else to Stop.");
if(!play.equalsIgnoreCase("play")) break;
}
}
How can I make it so I can end the loop? It's giving me an error that it cannot be used outside of a loop but I am confused because it is still in my loop? I assume it is something to do with the fact that it is in a main method but without the main method I get a different error on the part of my scanner code. (I am supposed to make a rock paper scissors game that ends at the end of the loop when the user chooses to stop. I don't know how to go about fixing this error.)
The break is indeed outside the loop. Your loop is this:
do {
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine(); //
} while (play.equalsIgnoreCase("play"));
You probably meant your code to be like this:
// no do {
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine(); //
// no }
while (play.equalsIgnoreCase("play")) { // no semicolon!
...
}
UPDATE
You seem to be confused by the two forms the while loop can take:
do { <code> } while ( <condition> ) - here, the code comes before the condition and is always executed at least once.
while ( <condition>) { <code> } - here, the condition comes first, and the code might not be executed even once.
Your example should look something like this to work:
Scanner scan = new Scanner(System.in); /* Create a scanner */
while (true) {
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
String play = scan.nextLine();
if (!play.equalsIgnoreCase("play")) {
break();
}
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
...
}
It looks like you want to read a first value before looping. So do this :
//do { // no need do
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine(); //
// } no need do
while (play.equalsIgnoreCase("play")) { // remove comma here
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
S
Final code wil be :
// these two lines allow to initialize "play" variable
System.out.print("Please enter Play if you want to play the game or anything else to Stop");
play = scan.nextLine();
while (play.equalsIgnoreCase("play")) { // (**) test "play" var to keep in the loop
// these 2 lines are good.
System.out.print("Choose your weapon [R]ock, [P]aper, or [S]cissors: ");
String rps = scan.nextLine();
...
...
...
...
...
...
// at the end of the loop, read again "play" var to decides if you stay or stop loop
System.out.println("Please enter Play if you want to play the game again or anything else to Stop.");
play = scan.nextLine(); // IMPORTANT
// but no need to break, because the play value will be tested by the enclosing while condition at (**)
// if(!play.equalsIgnoreCase("play"))
// break;
}
Your break is actually not in a loop. You should have a look at the syntax of do-while loops. Then, you can realise that the loop ends after the semicolon after while().
do {
// Do some stuff in a loop...
}
while(condition); // <-- Loop ends here
The relevant difference between a while loop and a do-while loop is that the former one is only entered when the given condition elevates to true while the latter one is always entered at least one.
while
Check condition whether statement in loop should be executed
Execute statement in loop and go to beginning
do-while
Execute statement in loop
Check condition to potentially start again.
You have a do-while loop.
do {
System.out.print("Please enter Play if you want to play
the game or anything else to Stop");
play = scan.nextLine(); //
} while (play.equalsIgnoreCase("play"))
And you don't have a break within this loop.
Your break statement is out of loop. In short, you may need to learn how to use loop from a good book.

Substract 1 after each loop end [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm new at java and i tried to make a Guess The Number game.
When the loop starts, i want to check if the user has any tries left.
if (remain > 1);
then after each end of the loop I want to subtract 1 from the tries.
I also tried to gather 1 after each loop ends.
byte tries = 5, remain=(byte)(--tries);
When user is out of tries i want to break the loop and break the game:
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
Here's my code:
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte tries = 5, remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1);
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
Code works perfectly but it won't break when user is out of tries.
tries variable should be initialized outside the while loop and the if statement was being closed using a ';'
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double number = (byte)(Math.random() * 21);
byte tries = 5; // tries should be initialized outside the loop
while(true){
// User input
System.out.print("Choose a number between 1 and 21 :");
byte user = scanner.nextByte();
byte remain=(byte)(--tries);
System.out.println(remain);
if (remain > 1) { // You were using ; and this if statement was closed
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
I think you are misunderstanding a lot of concepts. Here's a commented version :
public class Master {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// The number to found
double numberToFound = (byte)(Math.random() * 21);
// The user number will be stored here
byte userInput = 0;
// The number of tries left
byte tryLeft = (byte) 5;
do {
// Ask the User an number
System.out.print("Choose a number between 1 and 21 :");
userInput = scanner.nextByte(); // Store it
// Test the number
if (userInput > numberToFound) {
System.out.println("You are lower than the number!");
} else {
System.out.println("You are higher than the number!");
}
tryLeft--; // We remove one try
} while(tryLeft > 0 && userInput != numberToFound); // We loop until there are no more try OR we found the number
// Last time check (we check why we exited the loop)
// The user found the number
if (numberToFound == userInput)
System.out.println("You have guessed the number!");
else // The user has no more tries left
System.out.println("You haven't guessed the number!");
}
}
You should avoid using while(true) if you have a breaking condition for better readability.
You can try this code.
I changed some datatypes and added the decreasing of the remain variable inside the loop.
public class Master{
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int number = (int)(Math.random() * 21);
int tries = 5;
int remain = tries;
while(true){
System.out.print("Choose a number between 1 and 21:");
int user = scanner.nextInt();
// User input
System.out.println(remain);
if (remain > 1) {
//game
if (user==number){
System.out.println("You have guessed the number!");
break;
} else if (user < number)
System.out.println("You are lower than the number!");
else if (user > number)
System.out.println("You are higher than the number!");
--remain;
}
//Break if user is out of tries
else if (remain == 0){
System.out.println("You haven't guessed the number!");
break;
}
}
}
}
First of all, you can check if the "remain" is bigger than 0 and not 1, and your code will do the job as you planned (and you don't need to check == 0 at the else) :)
Second of all small comments to make your code more arranged:
Work with parameters that are comfortable to you like int (easier to debug and work with) you should use byte only if the code really needs it.
Move parameters that you use only to check them outside the loop like tries (think on that you will define this variable on every loop iteration and you don't need to).
Add to the params you are not going to change (like tries & number after you moved outside the loop) final it will be more clear that you are not going to change this param anymore.
Other than that looks great, good luck! :)

Java Wrong User Input Loop until correct

I have a problem validating the program. I have tried using, While/Switch but it is all the same. The issue is when a user enters the wrong input for example 5, it shows the error and then it lets them type it in again, but if they type in the wrong number again, the program does not validate. I can definitely copy the code again and again within it, but there should be an easier way.
I hope you understand what I am trying to achieve.
How could I make it so it is a continues loop?
// Choosing the right room
public static int rooms () {
int room;
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
// Displaying a message on the screen
System.out.println("What room are you in? ");
// Input
room = scanner.nextInt();
if (room==1) {
roomOne();
} else if (room==2) {
roomTwo();
} else if (room==3) {
roomThree();
} else if (room==4) {
roomFour();
} else {
System.out.println("Wrong room number, please enter the room number.");
room = scanner.nextInt();
}
//System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");
return room;
} // End Rooms
You are looking for a while loop, something like this.
I use a do ... while to execute the line at least once.
The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
This is a quick code note even test.
while (true) {
int room = scanner.nextInt();
if(room < 1 || room > 4) {
System.out.println("Wrong room number, please enter the room number.");
continue;
}
break;
}
if (room == 1)
roomOne();
else if (room == 2)
roomTwo();
else if (room == 3)
roomThree();
else if (room == 4)
roomFour();
Hope it helps, nevertheless you should read a little more about loops.
This is how you should set up a loop for input cleaning:
Define a boolean value and assign a true or false value
Make the while loop run on the boolean value
When input is "clean", set the boolean value to true

How to stop the method continuously looping

I am currently trying to complete a program with multiple classes in java that will allow the user to input information to help him or her book tickets, accommodation, parking, etc for a rock festival. I have started with one of the classes 'accommodation' to return the correct input of the user to the main class, however, I have found when I run the program and enter option 3, it immediately loops continuously which I have to terminate. I have searched online for a way to stop the loop, and for it to return the correct inputted information to no avail, I would appreciate any help to a very new new noob, before this loop turns me loopy!
Below is my main class and the class 'accommodation'. thank you in advance and apologies for any messy coding I have, as I have been trying various options as I have said before.
import java.util.Scanner;
import java.util.InputMismatchException;
public class clydeRockfest {
public static void main(String[] args) {
boolean quit = false;
Scanner in = new Scanner(System.in);
int choice; // Display the menu
int answer = 0;
Accommodation accommodation = new Accommodation();
//accommodation.getaccommodation();
do{
System.out.println("1\t Festgoers");
System.out.println("2\t Ticket");
System.out.println("3\t Accommodation");
System.out.println("4\t Transport");
System.out.println("5\t Parking");
System.out.println("0\t Quit");
System.out.println("Please enter your choice:");
//Get user's choice
choice=in.nextInt();
if(choice == 0)
quit=true;
//Display the title of the chosen module
switch (choice) {
break;
case 3: accommodation.getaccommodation();
System.out.println("You require " + answer + " accommodation.");
break;
case 0:
quit=true;
break;
default: System.out.println("Invalid choice, please choose again.");
} //end of switch
} //end of the main method
while(!quit);
} //end of class
}
public class Accommodation {
private String accommodation;
void getaccommodation(){
int no = 0; // no accommodation at all required
int self_Pitch = 0; // chosen if requiring a pitch
int tent = 0; // chosen if using a tent
int answer = 0;
int choice = 0;
boolean done = false;
System.out.println("Do you require accommodation?");
System.out.println();
// Answer validation loop
boolean validanswer = true;
while (!validanswer){
System.out.println("Enter:(1=NO, 2=SELF-PITCH, 3=TENT)");
System.out.println();
if(answer > 0 && answer < 4){
validanswer = true;
done = true;
}// ends if
else{
System.out.println();
System.out.println("That is not a valid answer, please choose again:");
System.out.println();
} // ends else
} //ends while
}
public void setaccommodation(String accommodation){
this.accommodation = accommodation;
}
Output:
Please enter your choice:
3
Do you require accommodation?
You require 0 accommodation.
1 Festgoers
2 Ticket
3 Accommodation
4 Transport
5 Parking
0 Quit
Please enter your choice:
you prime your loop by setting done=false but never set done = true so your loop will never end
You have two loops checking if user is done, and the condition of the first one (with the done) variable is never changed. Just remove this loop, and you should be fine.
Also, it looks like the condition for the second loop variable should be
if (answer > 0 && answer < 4)
to match your menu alternatives.
You never set done to true. It seems you may need to do it here:
if(answer >=0 && answer <=4){
validanswer = true;
done = true;
}
else{
//code
}
However, I'm not even sure you need that outer loop in the first place:
while(!done){
It seems redundant.

How would I create a "infinite" loops until the user decides to call it quits?

I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.

Categories