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
Related
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.
Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.
Goes from this class
if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
else {
System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
int answer = 0;
john[choice].toPass(answer);
if (answer== 1) {
System.out.println(answer);
map[x][y].removeJohnPlayer();
}
else { System.out.println(answer);
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
To this class
public int toPass(int right){
int hiddenNum = numram.nextInt(MAX_NUMBER);
Scanner input = new Scanner(System.in);
int numOfGuesses = 0;
int a = right;
do {
System.out.println("Enter a number by guessing: ");
int guessedNum = input.nextInt();
numOfGuesses++;
if (guessedNum == hiddenNum) {
System.out.println("Darn! Your number is matched. You may live.");
System.out.println("You have made " + numOfGuesses + " attempts to find the number!");
a = 1;
break;
} else if (guessedNum < hiddenNum) {
System.out.println("Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Try a smaller number");
}
} while (numOfGuesses < 3);
System.out.println(a);
return a;
}
Here
john[choice].toPass(answer);
you are ignoring the value returned by your toPass method.
Change it to:
answer = john[choice].toPass(answer);
BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.
i.e. change your method to public int toPass().
Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.
I'm really new to Java and most of my knowledge are self- taught. can you help me to figure out this.
Our teacher wants us to make a menu about Java. Where the output something like this..
Menu
1 - Java History
2- Java Keywords
3 - Java Arrays and so on. .
Do you want to read one (Yes/No):
//if yes
Please enter a menu number:
// then it will display an information..
//my problem is that how can I connect the new entered value to the first method so that I don't have write it all over again...
this is whats on my mind..
but im stuck..
import java.util.Scanner;
public class Program {
public static void main (String [] args) {
System.out.println("Please enter a number:");
int x = nextInt();
if (x == 1) {
for (int x = 5; x == 5;x++) // array of 1(first menu)
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 2) {
for loop of array 2
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
}
else if (x == 3) {
for loop of array 3
System.out.println ("Do you want to read another? (Yes/No):");
System.out.println ("Please enter a menu number:")
// return to if with it's new entered value....
else if (x ==4) {
for loop of array 4
else if (x == 5) {
for loop of array 5
else if (x == 6) {
for loop of array 6
else if (x == 7) {
for loop of array 7
else if (x == 8) {
for loop of array 8
else if (x == 9) {
for loop of array 9
else if (x == 10) {
for loop of array 10
else {
//exit the program
If I understand correctly, you would want to implement the While or do while statement in your program.
Example of While and Do While Loops
Im not really sure what you are trying to accomplish with your program but here is a little example I made quickly of how to utilize the for loop in your case. `import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean keepGoing = true; //As long as this is true the while statement will continue;
while (keepGoing) {
System.out.println("Enter a number");
int x = scan.nextInt();
//logic
if (x == 1) {
System.out.println("X is equal to 1");
} else if (x == 2)
System.out.println("X is equal to 2");
//prompts the user if they want to keep going.
System.out.println("Would you like to keep going? Y/N");
String decision = scan.next();
if (decision.equalsIgnoreCase("y")) {
keepGoing = true;
} else {
System.out.println("Quitting...");
keepGoing = false;
}
}
}
}
`
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.
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.