Creating a basic menu, why can't I get this right? -Java - java

I'm taking an Intro to Java class, and I haven't been having any trouble until now. I don't know if I'm just being a fool and the answer is simple but here goes.
I need to create a simple menu. I prompt the user, and then they enter an integer to choose one option. But there also needs to be an option to type "X" and exit the program.
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Math Study Guide!");
System.out.println("Which arithmetic table would you like to use?");
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("X) Exit the program");
int input = in.nextInt();
if (input <= 5 )
{if (input == 1){System.out.println("Addition");}
{if (input == 2){System.out.println("Subtraction");}
{if (input == 3){System.out.println("Multiplication");}
{if (input == 4){System.out.println("Division");}
else {System.out.println("You have exited");}
Testing it, whenever I type "X" it shuts down everything and doesn't tell me I've exited. Is there a general input I can use where you can enter either an int or a String?

As already stated in some comments, your probleme is the data-type. If someone enters 'X' in the program, it is expected to be an integer value, which it is not.
To get your Program working you need to alter your datatype from int to String
String input = in.next();
this will get you the input.
Now make a switch/case instead of your if-statements
switch (input) {
case "1" : System.out.println("Addition");
break;
case "2" : System.out.println("Subtraction");
break;
deafult: System.out.println("You have exited the program");
break;
}
If you are not familiar with the switch/case statement: case "1" checks if input equals "1". If true it prints out "Addition", after that it is important to make a break; otherwise it would go on checking if input equals "2" and so on.
the default branch is activated if nothing else matches. So your program would also write "You have exited the program" if your input was e.g. "r". If you don't want that, just add another case "x" and write your thing.

Related

How to stop a user from entering a letter in a switch case when the letter is the first input entered

When using a switch case with integers, I am able to successfully stop the user from crashing the program with a try/catch when they enter a letter (a, b, c, etc, not case specific). However, I can only stop it after an integer is entered. For this example, it is NOT my actual code, it is only an example as it is a general question. Secondly, I want to try and get it working with suggestions, not having it done for me:
int choice
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number");
System.out.println ("1: Example one");
System.out.println ("2: Example two");
System.out.println ("0: Exit");
choice = scan.nextInt();
Loop: for (;;)
{
switch (choice)
case 1: System.out.println ("Example one successful");
choice = scan.nextInt();
break;
case 2: System.out.println ("Example two successful");
choice = scan.nextInt();
break;
case 0: System.exit (0);
break Loop;
default: try
{
System.out.println ("Please enter a number")
choice = scan.nextInt();
}
catch (InputMismatchException error)
{
System.out.println ("Not a valid number: " + error);
choice = scan.nextInt();
}
If the user enters a "1", it outputs the proper text inside the case 1 block. The same goes for case 2 and case 0 to exit. It will loop properly and continuously like this:
Enter a number: 1
Example one successful
Enter a number: 1
Example one successful
Enter a number: 2
Example two successful
Enter a number: ghdrf
Not a valid number: java.util.InputMismatchException
Enter a number: 0
The try/catch works in catching the wrong input, all the other case work. The problem is if the user never enters an integer from the start and enters a letter instead. It will throw the InputMismatchException right away. The try/catch doesn't even try to catch it.
My thinking was because I assigned the scanner to read an integer from the start. I tried to start there. I originally tried this between the loop label and the switch statement as it is the only place I could put it to not get an error:
Loop: for (;;)
{
String letter = input.nextLine();
if(letter.matches("[1-9]*")
{
choice = Integer.valueOf(letter);
}
else
{
System.out.println("Invalid input");
}
switch (choice)
...
This worked somewhat in the same way as my try/catch except it was simply printing "invalid input" with each selection (because of my print statement, I know that). But the same problem was occurring. If a letter was input instead of an integer right off the bat, it would throw an InputMismatchException. I have a feeling it has something to do with what is in the scanner. I've tried experimenting with "next(), nextLine(), nextInt(), equals()" and I've tried parsing with "Integer.valueOf()" trying to get the current line in the scanner to check it or parse it.
This leads me to my questions:
Am I correct to assume that the scanner is reading the input and throwing the exception before I have a chance to catch it?
How do I read the first line in the scanner at the beginning of the program in order to check if it is an integer or a String? I'm not a big fan of skipping the first line because then it causes the user to have to input their number twice in order for the program to print out a message such as:
Enter a number: 1
Enter a number: 1
Example one successful
Any input is greatly appreciated, thank you!
Question #1: no. The problem is, that the exception occurs in those lines which are not surrounded by try-catch (e. g. before the loop, in case 1 or case 2).
Question #2: to read a line, use Scanner#nexLine(). There's no need to have the user to perform his input twice.
Hint: write a method that requests an int value from the user and that returns only, if he entered a correct value.
You have 2 calls to next int. You're only catching exceptions from one of them. You need to do it for both.
I'd put some thought into reorganizing this code a bit. You don't really need two calls to nextInt. You can do it with one by changing what things are in the loop and what aren't. Since you're a beginner I'll let you think about that for a bit rather than hand you the answer.

Ask for input again if wrong input is entered

I am new to Java programming. I want the program to ask for input again if wrong input is entered by the user. What must I do? Please help! Jump to the 'if else if' part if you want to avoid the mess... And not being rude but please don't request for closing the question if you can't answer.
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
}
else
{
System.out.println("Invalid input.");
}
It has been 28 days since you asked your doubt so I don't know if you have come across the answer or not but here's my solution.
To accept the correct input you need to make use of a while loop, loops are iterations in java which run for multiple number of times as per the given instructions. In this program I have incorporated a while loop whose condition is true always, so basically it is an infinite loop. If the inputted variant is correct and matches with any one of the if condition then the loop will break automatically because of the "break;" statement.
break; is a jump statement in java which allows you to terminate a loop when your requirements are met.
Given below is your required program code.
Hope this solves you query :)
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
while(true)
{
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
break;
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
break;
}
else
{
System.out.println("Invalid input.");
System.out.println("Please enter the variant again:");
}
}

How to go back to upper position in a program

I am trying to make node based big integer calculator in Java, and I want to re print the menu of calculator after operations. I thought of using goto but it gives error saying goto byte expected.
I am new in java, so can any one help me with the below demo code-
up:
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default:
goto up;
}
Thank you, I just want to reprint the menu.
You should use a simple while-loop for that. Maybe create a boolean as the running condition and set it to false, when the user types something else than 1 or 2.
Java does not support goto, as it is a reserved keyword.
Also, IMHO, using goto is not a great way to write a program.
A better approach would be to write a function which displays the menu and call that function whenever you want. Or just use a do-while loop.
Here is a way to look at "goto" in a java environment, using your code as the example:
public void addUp() {
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default: addUp();
}
}
Java doesn't use goto as it doesn't really fit into the Object-Oriented concept (I faced the same problem years ago when I made the switch from Basic). So you'll have to reconsider your code's logic to implement a loop of some sort.
Something like:
do {
// add an exit option to the menu
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
System.out.println("3. EXIT");
// continue with the same logic you had before
} while (i !=3)
I hope that helps.
note: if you lookup the keyword goto in Java documentation, you'll see that it's reserved but it doesn't do anything. They probably reserved it as a placeholder for these situations

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

Java validating a range of numbers from user input

I have been having problem with my validation, and it is stressing me out, I have done it in various ways with different loops, and the one I have as of now is this one, if I take out the IF statement if will function well for numbers, but since my program can only accept numbers from 1 to 5 I want to take the extra step into validating the number and then returning it. I try declaring the int option inside a loop but does not carry out to the return statement.
public int makeOption(){
int option;
System.out.println("Choose from the following options: ");
System.out.println("(1)Create entry || (2)Remove entry || (3)List entry || (4)List All || (5)Exit ");
while(!reader.hasNextInt()){
System.out.println("Choose a valid option.");
reader.next();
}
if(reader.nextInt()<1 || reader.nextInt()>5){
System.out.println("Choose a valid number from options.");
reader.next();
}
option = reader.nextInt();
System.out.println("You choosed: " + option);
return option;
}
Swap out your if statement for a switch statement:
int input = reader.nextInt();
switch(input)
{
case 1: // Do something
break;
// blah blah blah more cases.
default: System.out.println("Please enter a correct value.");
}
A note on your code
When you call reader.nextInt(), you're telling the stream to expect another int. You're not viewing the same value. You should store it in a variable, before using it.

Categories