I've ran into a weird issue.
I'm trying to make this code loop constantly until the user enters 4; when the user enters 4, I want to make it so that 'Quit_Detect' is set to false.
For some reason, it doesn't let me do that. The code still continuously loops until it is stopped manually.
Below is all of the code that I have used for this program along with some comments.
import java.util.Scanner; // Imports the scanner utility.
public class Start {
public static void main(String[] args) {
Scanner Reader = new Scanner(System.in); // Creates a new scanner.
#SuppressWarnings("unused")
boolean Quit_Detect;
Quit_Detect = true;
while (Quit_Detect = true)
{
int input; // States that input will have a datatype of 'int', or integer. Or, a whole number.
System.out.println("Please input your option.");
System.out.println("1. Door with a crack in it");
System.out.println("2. Normal Wooden Door");
System.out.println("3. Turn around");
System.out.println("4. Quit");
input = Reader.nextInt(); // Has the user define what the variable 'input' will be set to.
switch (input) // Uses the Variable 'input' to detect what case to follow.
{
case 1:System.out.println("First Option");
break;
case 2:System.out.println("Second Option");
break;
case 3:System.out.println("Third Option");
break;
case 4:Quit_Detect = false;
break;
default:System.out.println("Invalid option."); //Prints this if the user inputs any number other than 1, 2, or 3.
}
}
}
}
You should use:
while (Quit_Detect)
instead of:
while (Quit_Detect = true)
The first statement checks if Quit_Detect is true where the second sets the value of Quit_Detect to true.
Related
I've got a main menu I'm creating for a program using a switch statement. I'm try to set up Try and Catch Exception so that if a user enters a String rather than an Int, the program will tell the user this is not valid and prompt them to try again.
So far, I have gotten it to tell the user this is not valid whenever this occurs, but it is unable to go back and take an input from the user.
Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Subscription Manager:");
System.out.println("\n1. Enter new Subscription");
System.out.println("2. Display Summary of subscriptions");
System.out.println("3. Display Summary of subscription for Selected Month");
System.out.println("4. Find and display subscription");
System.out.println("0. Exit");
System.out.print("Please choose one of the options to proceed:");
try {
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("1. Enter new Subscription");
break;
case 2:
System.out.println("2. Display Summary of subscriptions");
break;
case 3:
System.out.println("3. Display Summary of subscription for Selected Month");
break;
case 4:
System.out.println("4. Find and display subscription");
break;
case 0:
System.out.println("Exiting Program...");
System.out.println("Goodbye!");
System.exit(1);
break;
default:
System.out.println("ERROR. Enter a selection from the options to continue!");
break;
}
} catch (InputMismatchException e) {
System.out.println("Enter a numerical value!");
sc.nextLine();
}
}
}
I have tried adding a do while loop, but I am met with the same issue still.
Thank you for reading!
What you need to do is to use a loop with the correct exit condition. For this specific case, I would recommend using do..while loop. Because this looks like a school assignment, I am not going to give you the full code but a small pseudocode.
int choice = 9999; // Declare this outside the do while loop so that you can access this variable in the while exit clause.
// Also initialize this so that you still have a value for choice in case of exception
do {
try {
int choice = sc.nextInt();
// DO YOUR SWITCH CASE AS YOU HAVE
}
catch(InputMismatchException e) {
// IN this case, choice is still 9999 for an error in the first run and some other integer in the subsequent runs of the loop. Just print an error message.
}
} while (choice != 0);
I am trying to make a currency conversion program which uses methods in one class. I have successfully managed to call my enterValues method from the mainMenu but when this method has finished, I need it to go back to the main menu. I receive the following NoSuchElement exception when calling my mainMenu method:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Conversion.mainMenu(Conversion.java:25)
at Conversion.mainMenu(Conversion.java:34)
at Conversion.main(Conversion.java:63)
Here is my code:
import java.util.Scanner;
public class Conversion {
int value;
public void mainMenu() {
int menuChoice;
Scanner menuScan = new Scanner(System.in);
System.out.println("1. Enter values and type -1 to stop");
System.out.println("2. Euros");
System.out.println("3. Dollars");
System.out.println("4. Yen");
System.out.println("5. Rupees");
System.out.println("6. Exit");
while (!menuScan.hasNextInt() || (menuChoice = menuScan.nextInt()) > 6) {
menuScan.nextLine();
System.err.println("Please enter a valid menu option 1 - 6: ");
}
switch (menuChoice) {
case 1:
enterValues();
mainMenu();
case 2:
}
}
public void enterValues() {
Scanner valueScan = new Scanner(System.in);
System.out.print("Enter value to convert: ");
value = valueScan.nextInt();
System.out.println("Value entered. Returning to main menu.");
valueScan.close();
}
public static void main(String[] args) {
Conversion conv = new Conversion();
conv.mainMenu();
}
}
Several issues at risk with your code:
You're creating more than one Scanner off of System.in and then closing one of them before you're done with the other Scanners, risking closing System.in.
You're mixing nextInt() with nextLine() calls on the Scanner without first handling the end of line token properly
You're using recursion where you don't want to use it -- having a method call itself.
Suggestions:
Use one and only one Scanner based on System.in and don't close it until your done.
Pass it into other methods that need it.
Every time you call nextInt() on it, call nextLine() too immediately after to handle the end of line token.
Don't use recursion here -- there are better and safer ways to re-call the main menu.
It has to do with you making more then 1 objects of your System.in. You should try to use only one if needed, and also use the correct method for the element youre trying to read (integers in your case). Also i would design the class a little different, a do while loop would be more appropriate, you also dont call break in your switch, causing it to also execute case 2 no matter wat. Here is some sample code for you to work with:
public class Main {
private int value;
private int menuChoice;
private Scanner menuScan;
private boolean stop = false; // program stops when stop == true
public static void main(String[] args){
Main main = new Main();
main.runProgram();
}
public void printMenu() {
System.out.println("Enter values and type -1 to stop");
System.out.println("1. Euros");
System.out.println("2. Dollars");
System.out.println("3. Yen");
System.out.println("4. Rupees");
System.out.println("5. Exit");
}
public void runProgram() {
stop = false;
menuScan = new Scanner(System.in);
do {
printMenu();
menuChoice = menuScan.nextInt();
switch(menuChoice){
case 1:
enterValues("Euro"); // enter the values and give it a string with the type of value that is being entered, so you can check for this later
break;
case 2:
enterValues("Dollar");
break;
case 3:
enterValues("Yen");
break;
case 4:
enterValues("Rupees");
break;
case 5:
System.out.println("Stopping program");
stop = true;
break;
default:
System.out.println("Please enter a valid number");
break;
}
}while(!stop);
}
public void enterValues(String valueType) {
System.out.print("Enter value to convert: ");
value = menuScan.nextInt();
System.out.println("Value entered. - run your conversion now. (Returning to main menu for now)");
/////// run your conversion here or create a method for this and call it now.
}
}
note i only used 1 class scoped System.in and no recursion for the main menu, its all in the loop.
So, I have some code which, when simplified, is this:
import java.util.scanner
private Scanner input;
int enterInteger()
{
System.out.println("Enter the quantity");
return input.nextInt();
}
String enterString()
{
return input.nextLine();
}
void main()
{
System.out.println("Enter option: 1) Add Quantity\n2)Edit Item");
String input = enterString();
switch (input)
{
case "1":
enterInteger();
break;
case "2":
//Do whatever
break;
default:
System.out.println("Invalid!");
main();
break;
}
}
So, whenever the user enters the option as 1, it loads enterInteger() that asked the user, and returns, an integer.
However, when this happens, and the user enters the integer and presses enter, the code then begins executing the default: case. When I add a breakpoint the value of option is "", so that's obviously why the default: executes, but I can't see how to prevent it.
I know it's something dumb, so thank you.
I don't know the reason yet, But in the past I had to work with only nextLine() and parse with Integer.parseInt() when necessary.
By the way, You haven't initialized the Scanner.
Scanner input = new Scanner(System.in);
I'm making a school assignment and this time around I thought about using a switch statement since it looked more efficient.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
This is my code for the entire class so far:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
private int option;
public static void main(String[] args) {
Test t = new Test();
t.start();
t.optionMenu();
}
public void start() {
System.out.println("Make your choice:");
System.out.println("1: Play");
System.out.println("2: Options");
System.out.println("3: Exit");
}
public void optionMenu() {
try {
Scanner sc = new Scanner(System.in);
this.option = sc.nextInt();
System.out.println(this.option);
} catch (InputMismatchException e) {
System.out.println("Please enter a number");
optionMenu();
}
switch (this.option) {
case 1:
System.out.println("Game starting...");
break;
case 2:
System.out.println("Loading options");
break;
case 3:
System.out.println("Game exiting...");
System.exit(0);
break;
default:
System.out.println("Enter a valid number (1, 2 or 3");
break;
}
}
}
Any help would be much appreciated, thanks!
When you call sc.nextInt() without first asking if (sc.hasNextInt()), you are open to some strange behavior when end-users start typing unexpected input, such as letters. In this case the scanner would not advance its reading pointer, so your program will get stuck reading the same incorrect output.
To fix this issue, add a loop that "clears out" the invalid entry before attempting to read an int again, like this:
while (!sc.hasNextInt()) {
System.out.print("You need to enter an integer.");
sc.nextLine(); // Clear out the bad input
}
int val = sc.nextInt(); // At this point we know that sc.hasNextInt(), because that's the loop condition
Another point is that it is not a good idea to do with recursion what can be done with iteration: the recursive call to optionsMenu is going to accumulate as many levels of invocation as the number of times the end-user enters an incorrect value, so a very persistent user could theoretically force a stack overflow on your program by entering invalid data repeatedly.
Using the code fragment above would free you from the need to call optionsMenu recursively, and also from catching the input exception.
It's just something basic but if I enter a letter for example and after that number 1 for example it would return case 1 twice?
I'm not sure what you mean here. Firstly, your idea works, this code should be fine!
Second, if you enter anything besides just the number 1, 2, or 3, you will go to the "default:" block of code. Since you are prompting the user again if they fail, typing "a" or "a1" into the prompt just shows the menu again. The user needs to just type "1", "2", or "3" to successfully select a menu option.
I am wondering how to print a particular sentence depending on user input.
In the scenario below, if the user enters "B" I would like to print the words "You have selected B" however if the user selects C I would like to print the word "You have selected C".
import java.util.Scanner;
public class Trial extends Register
{
//I want to load the register which will be option B
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter A to make a purchase & receive your change");
System.out.println("Enter B to load the Register");
System.out.println("Enter C to write the contents of the Register to a
web Page");
System.out.println("Enter D to exit the program");
}
How about:
String input = // read input from scanner;
if(input.length() == 1) {
switch(input.charAt(0)) {
case 'A':
// make purchase
break;
case 'B':
// load register
break;
// Similarly case C and D
default:
// possibly invalid input as well
}
} else {
System.out.println("Invalid input");
}
If you are using Java 7+, you can use a switch statement.
If you use an earlier vrsion, you need to use several if statements.
As for the Scanner, you can read this tutorial to get started and have a look at this example.