How to go back to upper position in a program - java

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

Related

how do i keep taking choices in switch case until exit choice is entered in java [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 4 years ago.
I want to keep taking choices from the user until he gives an exit statement.
How can I come out of the while loop if I use it in this code?
Is there any other way to take choice from the user than switch case:
And if I try to use while loop for this then it is going in an infinite loop:
Code:
import java.util.Scanner;
class lib
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String c;
int j=5,a=5,s=5,cg=5;
int d=0;
System.out.println("Available Copies :");
System.out.println("java=5,ada=5,sp=5,cg=5");
System.out.println("enter book title");
//System.out.println("enter exit for exit if don't want to search");
c=in.nextLine();
while(d==0)
{
switch(c)
{
case "java":
System.out.println("author is herbert");
System.out.println("price :500");
j--;
break;
case "ada":
System.out.println("author is corman");
System.out.println("price :600");
a--;
break;
case "sp":
System.out.println("author is dhamdhire");
System.out.println("price :550");
s--;
break;
case "cg":
System.out.println("author is pearson");
System.out.println("price :700");
cg--;
break;
case "exit":
d++;
break;
default:
System.out.println("book not available");
}
}
if(j!=0)
System.out.println("number of available copies is"+j);
}
If you want to keep taking input from the user until they give the exit command then you need to keep taking input inside the while loop. Move c=in.nextLine() into the while loop right before the switch statement.
If you want to prompt the user as well then add a print statement at the end of the loop right after the switch statement ends, and instead move c=in.nextLine() to the end of the while loop right after the print statement. Something like:
System.out.print("Enter the title of another book: ");
c=in.nextLine();
I think what your looking for is moving your nextLine inside the while loop.
This part of the code:
//System.out.println("enter exit for exit if don't want to search");
c=in.nextLine();
while(d==0)
{
.....
To this:
//System.out.println("enter exit for exit if don't want to search");
while(d==0)
{
c=in.nextLine();
.....

Creating a basic menu, why can't I get this right? -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.

Calling previous switch in Java

I'm making a simple command line system where the user is supposed to be able to choose what they want to do. Therefore I've made a switch that takes a number as input and outputs whatever I choose, although I have now clue on how to return the user to the place where they can input again.
Let's say two of the cases looks like this:
case 6:
System.out.println("----- List of available Systems: ----- ");
break;
default:
System.out.println("You pressed a non-existing number. Please try again.");
break;
}
Now if the user (me) types any number above 6 it goes to the default and stops there. Is there anyway to make it jump back to the first "Menu" that asks for input?
Thank you in advance.
You can wrap it in a loop, e.g. a while:
while (var < 1 || var > 6) {
switch(var) {
...
}
}
However, this way, you need to make sure, that you won't be stuck in an infinite loop. This can be solved, e.g. by using a label:
end: while (var < 1 || var > 6) {
switch (var) {
case 1:
// do something
break end;
...
default:
System.out.println("Please try again.");
break;
}
}
This way, the break statements will break out of the while loop. Java labels are basically a very limited version of goto.
How about something more verbal..
int myno;
Scanner scanner =new Scanner(System.in);
boolean exit = false;
while(!exit){
System.out.println("1. Menu 1");//Modify your menu
System.out.println("2. Menu 2");
System.out.println("3. Menu 3");
System.out.println("4. Menu 4");
System.out.println("5. Menu 5");
System.out.println("6. Menu 6");
myno = scanner.nextInt();
switch(myno){
case 1 :
//do something
break;
case 2 :
//do something
break;
case 3 :
//do something
break; //add for remaining cases
case 7 :
exit = true;//for exit
break;
default :
// do something //set exit = true if you what to end the program for other inputs
}
}
try this

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.

Switch returning same statement multiple times

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.

Categories