I'm working on simple Calculator app on Java. When user enter 0(which returns info no math operator), i want to restart my function. But when I do it throws NoSuchElementException when debug pointer comes to int operationInput = sc.nextInt(); Here is the my whole code block. I tried try catch but it stucks. Maybe it cannot re-identify a variable because it doesn't quit of that code block.
static Object mathOperators() {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a number for choosing operation(if you don't know what operation equals to which number click 0): ");
int operationInput = sc.nextInt();
sc.close();
switch (operationInput) {
case 0:
System.out.println("1: Addition - 2: Subtraction - 3: Multiplication \n"
+ "4: Division - 5: Modulus");
return mathOperators();
case 1:
System.out.println(additionCalc());
break;
case 2:
System.out.println(substractionCalc());
break;
case 3:
System.out.println(multiplyCalc());
break;
case 4:
System.out.println(divisionCalc());
break;
case 5:
System.out.println(modulusCalc());
break;
default:
System.out.println("Please enter a valid number");
break;
}
return 0;
}
You can use only one Scanner(System.in) in your app. You must close the scanner before calling "break" in your switch cases.
Related
I am making this simple calculator program using switch statements and methods. But when the user presses any option (which is correct), it does not read the case and goes straight to the default case.
I've done the same thing before, but without any class file or methods. I'm new to methods so I just tried to do the same thing but it's not working properly.
NewClass cal = new NewClass();
Scanner in = new Scanner(System.in);
System.out.println("Press 1 for Division.\nPress 2 for Multiplication.\nPress 3 for Addition.\nPress 4 for Substraction.");
char c = in.next().charAt(0);
System.out.println("Enter First Value : ");
int a = in.nextInt();
System.out.println("Enter Second Value : ");
int b = in.nextInt();
switch (c){
case 1:
cal.division(a, b);
break;
case 2:
cal.division(a, b);
break;
case 3:
cal.add(a, b);
break;
case 4:
cal.sub(a, b);
break;
default:
System.out.println("Invalid entry.");
break;
}
output:
Press 1 for Division.
Press 2 for Multiplication.
Press 3 for Addition.
Press 4 for Substraction.
Enter your selection : 3
Enter First Value :
4
Enter Second Value :
5
Invalid entry.
BUILD SUCCESSFUL (total time: 9 seconds)
There is no need to convert user input to a char, as java switches can handle ints. The following code will fix your issue:
NewClass cal = new NewClass();
Scanner in = new Scanner(System.in);
System.out.println("Press 1 for Division.\nPress 2 for Multiplication.\nPress 3 for Addition.\nPress 4 for Substraction.");
int c = in.nextInt();
System.out.println("Enter First Value : ");
int a = in.nextInt();
System.out.println("Enter Second Value : ");
int b = in.nextInt();
switch (c){
case 1:
cal.division(a, b);
break;
case 2:
cal.division(a, b);
break;
case 3:
cal.add(a, b);
break;
case 4:
cal.sub(a, b);
break;
default:
System.out.println("Invalid entry.");
break;
}
Scanner input = new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z = input.nextInt();
switch (z) {
case 1:
System.out.println("your result is" + (x + y));
break;
case 2:
System.out.println("your result is" + (x - y));
break;
case 3:
System.out.println("your result is" + (x * y));
break;
case 4:
System.out.println("your result is" + (x / y));
break;
default:
System.out.println("choose the option from listed above");
break;
}
above code is for calculator in switch...
query is :
how can i call the switch function again in default case ?
Well, you can't execute the switch statement again because that does not solve the problem. z's value does not change, so it will always go to the default branch no matter how many times you re-execute the switch.
I suggest to put the whole thing in a loop and break out of the loop for cases 1-4.
loop:
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break loop;
case 2 :
System.out.println("your result is"+(x- y));
break loop;
case 3 :
System.out.println("your result is"+(x* y));
break loop;
case 4 :
System.out.println("your result is"+(x/ y));
break loop;
default :
System.out.println("choose the option from listed above");
break;
}
}
Note that I wrote break loop instead of break. break will just break out of the switch statement. This is why I added a label loop: before the loop starts, so that I can break out of the loop, instead of the switch, later.
Some corrections of your terminology
In Java, there are technically no functions. Functions must be outside of a class. There are only "methods" in Java. They look like this:
public static void someMethod(int somePar) { }
switch is neither a function nor a method, so you can't "call" it. switch is a control structure that is "executed" or "run".
You can do like this:
public void promptUser(){
Scanner input=new Scanner(System.in);
boolean validOption = false;
while(!validOption){
validOption = true;
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/");
int z=input.nextInt();
switch(z){
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
default :
System.out.println("choose the option from listed above");
validOption = false;
break;
}
}
}
I prefer using a loop so you won't be stacking a lot of calls to the same method over and over, thus you can avoid OutOfMemoryError.
Let's assume your code is in a function called calculate()
There are a few ways you could do this.
Recursively:
Just call the function again in the switch.
default :
System.out.println("choose the option from listed above");
calculate();
return;
Return a value and loop:
Change the function so it returns a value. For example, return true if is does anything but default, and false if it hits default. Then, in the logic that calls calculate(), put it in some sort of loop.
bool doLoop = true;
while (doLoop)
{
doLoop = !calculate()
}
You could put it inside a loop, for example a do ... while loop, and you may capture a key as ending condition.
do {
// your code here
} while(ending_condition);
while(true)
{
Scanner input=new Scanner(System.in);
System.out.println("please choose the operator");
System.out.println("1-->+ \n2-->- \n3-->* \n4-->/ \n5-->Exit");
int z=input.nextInt();
switch(z)
{
case 1 :
System.out.println("your result is"+(x+ y));
break;
case 2 :
System.out.println("your result is"+(x- y));
break;
case 3 :
System.out.println("your result is"+(x* y));
break;
case 4 :
System.out.println("your result is"+(x/ y));
break;
case 5 :
System.exit(0);
default :
System.out.println("choose the option from listed above");
break;
}
}
I Want to create a condition that checks were the input is a integer ranging from 1 to 5.
but it keeps saying input matching exception, can you guys help?
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
System.out.println(">> You have selected ["+choice+"]");
//loops until input is an integer ranging from 1 to 5
while(!scan.hasNextInt() && choice>0 && choice<6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
break;
}
}
}
Try this:
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
//input variable
String in;
//loops until input is an integer ranging from 1 to 5
while (scan.hasNextLine()) { //checks if there is a new line of input
in = scan.nextLine().trim(); //scans that line
if (!in.matches("^[1-5]$")) { //tests if input is a single positive digit 1-5
System.out.println(">> You put wrong input");
continue;
}
int choice = Integer.parseInt(in);
System.out.println(">> You have selected ["+choice+"]");
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
}
}
}
}
I have slightly altered your code to not only keep persisting the user for a valid input, but also correctly parse that input to avoid any errors. I also removed the default part of the switch block, only because the input validation prior eliminates the need for it.
I have not tested this code, but it should work properly :)
You are currently not updating the choice variable for each iteration, but rather only using the initial value. Furthermore, you're iterating until scan DOES NOT have an int, i.e. !scan.hasNextInt() and I guess you're intention is actually the opposite.
public static void main(String[] args) throws Exception {
//scanner for input
Scanner scan = new Scanner(System.in);
int choice;
//loops until input is an integer ranging from 1 to 5
while(scan.hasNextInt() && (choice = scan.nextInt()) > 0 && choice < 6){
switch (choice) {
case 1:
databaseInsertRecord();
break;
case 2:
databaseSelectAll();
break;
case 3:
databaseSearchRecord();
break;
case 4:
databaseUpdateRecord();
break;
case 5:
databaseDeleteRecord();
break;
default:
System.out.println(">> You put wrong input");
}
}
}
Hope it helps!
I was having some problem when trying to do a try catch for do while loop:
try{
do {
System.out.println("Enter your option: ");
choice = sc.nextInt();
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
} while (choice != 6);
}catch(InputMismatchException e){
System.out.println("Please enter option between 1-6.");
}
What I am trying to do for the do while loop is when user entered anything other than 6 which is terminate, it will keep prompting for user input. For each case, it will go to certain method.
Then, I tried to do a try catch for InputMismatchException because my Scanner is taking integer from user input. However, after I entered alphabet instead of integer, the program just terminated itself. I am trying to do like when user entered alphabet, it will keep on prompting user for correct input.
Any ideas? Thanks in advance.
I was thinking if I should make another do while to wrap the entire try catch?
Do like :
try {
choice = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("Please enter option between 1-6.");
sc.next();
continue;
}
If user enters a invalid input it will go to the catch block and will continue the loop. Remove the outer try catch block. Its not required
To handle characters and and invalid numbers you could do something like this:
do {
System.out.println("Enter your option: ");
try{
choice = sc.nextInt();
catch(InputMismatchException e){
choice = 0;
sc.next();
}
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Please enter option between 1-6.");
break;
}
} while (choice != 6);
While writing code for my program I thought of testing the first part before moving on and writing the operations. Although I have the user input, but I want the options to be displayed after each operation (add, deltete..) is done untill the users presses exit. How do I modify my code to do it?
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n Exit");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//int choice;
System.out.println("Enter your Choice : ");
Scanner sc = new Scanner(System.in);
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Getting ready to Add a Record ");
//set();
break;
case 2:
System.out.println("Getting ready to Delete a Record ");
//delete();
break;
case 3:
System.out.println("Getting ready to Update a Record ");
//update();
break;
case 4:
System.out.println("Here is your record ");
//display();
break;
case 5:
System.out.println("Out we go.");
System.exit(0);
//exit();
break;
default:
System.out.println("Try again");
break;
}
} while ( choice > 5 || choice < 1 );
}
}
Simply change your while condition to:
} while ( choice > 0 && choice < 5 );
First make sure your scanner really has an int, use sc.hasNextInt() to validate the user entered a number. To end the do/while loop at "5.Exit", just have it like do{...}while(choice!=5). Code below is not tested.
import java.io.*;
import java.util.*;
public class Records {
public static void main(String[] args) {
int choice;
do {
System.out.println("1.Add \n 2.Delete \n 3.Update \n 4.Show \n 5.Exit");
System.out.println("Enter your Choice : ");
choice = -1;
Scanner sc = new Scanner(System.in);
// validate the next thing in your scanner is an int
// otherwise, sc.nextInt() might cause an exception
if (sc.hasNextInt()){
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Getting ready to Add a Record ");
// ...
break;
case 2: System.out.println("Getting ready to Delete a Record ");
// ...
break;
case 3: System.out.println("Getting ready to Update a Record ");
// ...
break;
case 4: System.out.println("Here is your record ");
// ...
break;
case 5: System.out.println("Out we go.");
// skip System.exit(0), your main method ends
// automatically when you leave your do/while loop
break;
default: System.out.println("Try again");
break;
}
}
// if choice == 5 it ends, otherwise, starts over...
} while ( choice != 5 );
}
}
Although I have the user input, but I want the options to be displayed
after each operation (add, deltete..) is done untill the users presses
exit.
You can set int flag=0; and when user selects exit option set flag to 1 to tell loop to exit.As of now you are already breaking out for number > 5 or < 1 in default case so no need to put that condition in while.
int flag=0;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=1;//Set flag to 1 if user enters 5
break;
...
} while ( flag!=1 );//Exit the loop when flag==1
//Or directly while ( choice!=5 );
Serious EDIT
As Java Programmer I should probably suggest you to use boolean primitive type for flagging.
boolean flag=true;//Declare outside the loop
do{
...
case 5: System.out.println("Out we go.");
flag=false;//Set flag to 1 if user enters 5
break;
...
} while (flag);//Exit the loop when flag==false
One More thing:
Surround code with try-catch to leave out invalid inputs and prompt again for input.
Most of the times it's not recommended to swallow the Exception.
do{
try{
....//Your Switch case
}catch(InputMismatchException e){}
} while (choice !=5);//But remove System.exti(0); from your switch statement
Simply make your while loop as:
} while ( choice!=0 );(The Wrong one)
Correction:
} while(choice!=0 && choice<=5)