This is probably very simple, however I have completely blanked and would appreciate some pointers. I'm creating a small game we have been assigned where we select numbers and are then provided a target number to try and reach using the numbers we selected. Inside my while loop once my condition hits 6 it asks the user to generate the target number, however once they do it prints the same string again "Generate the final string" how do I print this only once?
Here is the code if it will help.
while (lettersSelected == false) {
if (finalNum.size() == 6) {
System.out.println("3. Press 3 to generate target number!");
} // Only want to print this part once so it does not appear again.
Scanner input = new Scanner(System.in);
choice = input.nextInt();
switch (choice) {
case 1:
if (finalNum.size() != 6) {
largeNum = large.get(r.nextInt(large.size()));
finalNum.add(largeNum);
largeCount++;
System.out.println("Numbers board: " + finalNum + "\n");
}
break;
It can be done very easily.
boolean isItPrinted = false;
while (lettersSelected == false) {
if ((finalNum.size() == 6) && (isItPrinted == false)) {
System.out.println("3. Press 3 to generate target number!");
isItPrinted = true;
}
The condition if (finalNum.size() == 6) is satisfied first and so the string is printed. However, during the next iteration of the while loop, the size of finalNum has not changed as the contrary of the condition is checked in the case 1 of the switch and the size is not changed anywhere between these two statements.
You can add a flag variable and set it to true, add a check for that variable in the if contidion and if the if-clause is entered, set the variable to false:
boolean flag = true;
while (lettersSelected == false) {
if (finalNum.size() == 6 && flag) {
System.out.println("3. Press 3 to generate target number!");
flag = false;
}
// ...
}
Related
I am working on a to do list and am currently stuck making a menu. The menu receives input from the user of the numbers 1-6 and carries out a specific task associated with that number(int). That's the perfect world scenario, so I need the menu to be able to take non integer values and not be bricked as well as display an error message to the user. I think I have created an efficient way of asking the user for integers without bricking the program but I cannot determine what my return statement should be in order to utilize the method in the main. I'll use it in a switch statement like this:
while (true) {
switch (getMenuOption()) {
case 1:
etc
This is the current method that I have for the getMenuOption. What return statement should I use, or is there a more efficient way to carry this out?
package project1_martinez_adriel;
import java.util.Scanner;
public class getMenuOption {
public static int getMenuOption() {
Scanner input = new Scanner(System.in);
System.out.println(" 1. Create a new item \n 2. Mark an item as in progress \n 3. Mark an item as completed \n 4. List all to do items \n 5. Remove completed items \n 6. Exit \n What would you like to do? \n ");
String value = input.nextLine();
int num;
try {
num = Integer.parseInt(value);
if (!(num == 1 || num == 2 || num == 3 || num == 4 || num == 5 || num == 6)) {
System.out.println("ERROR! Invalid choice! \nPlease enter a valid choice BETWEEN 1 & 6: ");
}else if (num == 6){
System.exit(0);
}
} catch (NumberFormatException e) {
System.out.println("ERROR! Please enter a valid INTEGER between 1 & 6.");
}
return //What do I put here!?
}
how about cleaning it up to be
if (num < 1 || num > 6) {
System.out.println("ERROR! Invalid choice!...");
}
then later
return num;
The code in your switch statement should process the options between 1 && 6 including 6 being System.exit (0);
I would even have the error messages in the switch default block
edit
num should also be initialized with a value, something like
int num = -1;
So after some clean up, frustration, & long hours I have come up with this, including the switch statements:
Scanner input = new Scanner(System.in);
boolean validInput = false;
do {
System.out.print("Enter an integer: ");
int num;
try {
num = input.nextInt();
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6: // cascading case statement example
validInput = true;
break;
default:
System.out.println("ERROR! Please enter a valid choice BETWEEN 1 & 6 (inclusive): ");
num = input.nextInt();
break;
}
} catch (Exception e) {
/* input.next() to move the Scanner forward. */
System.out.println(input.next() + " was not valid input.");
System.out.println("ERROR! Please enter a valid INTEGER between 1 & 6.");
}
} while (!validInput);
input.close();
}
}
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
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.
My program contains a few options that the user can select via the input of a number which allows them to complete a specific task. Currently, my code is set up with if and else if loops to complete task if a certain number of input. However, at the minute the program terminates after one task. I want the user to be able to input another number to complete another task. I have tried surrounding the code with a while loop and an exit option to allow the user to escape the loop and end the program, but this is not working and results in a "java.util.NoSuchElementException". The program works fine without the while loop.
This is an example of the current code which hopefully conveys what I mean:
System.out.println("Enter one of the following commands:");
System.out.println("1 - something..");
System.out.println("2 - something else..");
System.out.println("3 - exit");
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choiceentry = scanchoice.nextInt();
while (choiceentry != 3) {
if (choiceentry < 1 || choiceentry > 3) {
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
}
So I want to get into this loop, and only exit to terminate the program. I'm hoping that the while loop would take the user back to a menu, allowing you to select another option, however this is not working. What is wrong with this code? And how can I implement this idea?
Thanks in advance!
Use Scanner#hasNextInt() before you call Scanner.nextInt() to get rid of the NoSuchElementException
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
hasNextInt() returns true only if the next token is a valid int
You can do like this
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
}
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
I have changed it to use switch statements, since they come handy in getting input data
You are only asking the user to pick another menu item if choice is < 1 or > 3
you have to set this code in an else statement`:
while (choiceentry != 3) {
else if(choiceentry == 1) {
// ..do something
}
else if(choiceentry == 2) {
//..something else
}
else if(choiceentry == 3) {
//...exit program
}
else{
System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
choiceentry = scanchoice.nextInt();
}
}
If you want your program to continue prompting the user to select a task you'll need to move that prompt as well as your nextInt() call to somewhere inside your loop yet outside of an if statement so that it will always be invoked on each iteration.
As Mr Phi suggested in the comments, a switch statement would be a better alternative to your current if-else structure. It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values.
I'd also add that a do-while might be more suitable for this task. This way you won't need to code your prompt for a choice twice.
int choiceentry;
do {
System.out.println("Enter \"1\", \"2\" or \"3\"");
choiceentry = scanchoice.nextInt();
switch (choiceentry)
{
case 1:
// do something
break;
case 2:
// ..something else
break;
case 3:
// .. exit program
break;
default:
System.out.println("Choice must be a value between 1 and 3.");
}
} while (choiceentry != 3);
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.