Java Try-Catch Exception Calculator - java

So I'm trying to make a user input calculator using try-catch and exception. The program keeps on repeating and couldn't get the actual input for the numbers and it also includes the statement Wrong input. Please try again.
Any idea on how to fix this?
import java.util.*;
public class Calculator
{
public static void main(String[] args) {
int x=1;
do {
try {
System.out.println("Menu");
System.out.println("1-Addition");
System.out.println("2-Subtraction");
System.out.println("3-Multiplication");
System.out.println("4-Divison");
System.out.println("5-Modulos");
System.out.println("6-Exit");
System.out.println("Choose option: ");
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.print("Input two numbers:");
String dimension = scan.nextLine();
String[] parts = dimension.split(" ");
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);
int c=a+b;
System.out.println("Sum = " +c);
break;
case 2:
System.out.print("Input two numbers:");
String dif = scan.nextLine();
String[] difference = dif.split(" ");
int num1 = Integer.parseInt(difference[0]);
int num2 = Integer.parseInt(difference[1]);
int d=num1-num2;
System.out.println("Difference = " +d);
break;
case 3:
System.out.print("Input two numbers:");
String multi = scan.nextLine();
String[] product = multi.split(" ");
int num3 = Integer.parseInt(product[0]);
int num4 = Integer.parseInt(product[1]);
int p=num3*num4;
System.out.println("Product = " +p);
break;
case 4:
System.out.print("Input two numbers:");
String div = scan.nextLine();
String[] quotient = div.split(" ");
int num5 = Integer.parseInt(quotient[0]);
int num6 = Integer.parseInt(quotient[1]);
int q=num5/num6;
System.out.println("Quotient = " +q);
break;
case 5:
System.out.print("Input two numbers:");
String mod = scan.nextLine();
String[] modulo = mod.split(" ");
int num7 = Integer.parseInt(modulo[0]);
int num8 = Integer.parseInt(modulo[1]);
int m=num7%num8;
System.out.println("Modulos = " +m);
break;
case 6:
System.out.println("Now exiting program...");
break;
}
} catch (Exception e) {
System.out.println("Wrong input. Try again.");
}
} while (x==1);
}
}

You need to do this
int choice = Integer.parseInt(scan.nextLine());
because you are reading next input with readline()
String dimension = scan.nextLine();
and \n is already present it the stream when you enter your option with nextInt() because nextint() never reads the \n which you leave behind by pressing Enter button.

You should add:
scan.skip("\n");
right after
int choice = scan.nextInt();
Why? Because nextInt() reads next integer from input. And it leaves new line character at the end on the input. It's like:
1<enter>
After that you invoke scan.nextLine() which reads everything up to next new line character. In fact there is 1 new line character in the buffer. And here your nextLine() reads an empty string.
To solve that issue you have to skip buffered new line characters with scan.skip("\n").
EDIT:
in addition, your code doesn't allow you to exit, because you're not changing your x variable. Try to change it after System.out.println("Now exiting program...");. It will work ;)

This will help you to identify root cause:
} catch (Exception e) {
System.out.println("Wrong input. Try again.");
e.printStackTrace();
}

Related

Calculator Java Input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm trying to make a calculator in java that can multiply subtract and add depending if the user wants that they can choose what they want. For some reason its giving me a weird output
Code
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.nextLine();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a * b);
break;
default:
System.out.print("Invalid input!");
}
}
}
Output
Enter first number- 2
Enter second number- 2
Do you want to multiply, add, divide, or subtract? Invalid input!
Like I didnt even type Invalid input it just does it by itself for some reason
There can be input left in the scanner before you request a value. In this case, the line break marks the end of the integer, but is not consumed as part of the integer. The call to nextLine() sees there is already an unused line break at the end of the buffer and returns that result. In this case, an empty string is returned. One way to fix this is to consume that unused line break first before requesting the next line or requesting a full line then parsing an integer from it.
Scanner scan = new Scanner(System.in);
// Always request a full line
int firstInt = Integer.parse(scan.nextLine());
int secondInt = Integer.parse(scan.nextLine());
String option = scan.nextLine();
// Use an extra call to nextLine() to remove the line break causing the issues
int firstInt = scan.nextInt();
int secondInt = scan.nextInt();
scan.nextLine(); // Consume the unused line break
String option = scan.nextLine();
sc.nextInt() does not read the enter key that you entered, so sc.nextLine() will read that new line and return it. Use sc.next() instead of sc.nextLine() to avoid this issue. Your code also multiplies the numbers when the user inputs add, so I changed that as well.
import java.util.Scanner; // Import the Scanner class
public class calculator {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a = sc.nextInt();
System.out.print("Enter second number- ");
int b = sc.nextInt();
System.out.print("Do you want to multiply, add, divide, or subtract? ");
String c = sc.next();
switch(c) {
case "multiply":
System.out.print(a * b);
break;
case "add":
System.out.print(a + b);
break;
default:
System.out.print("Invalid input!");
}
}
}

Data entry problem with incorrect result?

Seeing the code.
When I start the program, it doesn't let me insert the scanner class input into the switch, how come?
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
switch (select) {
case 1:
System.out.println("first name:");
String n = in.nextLine();
System.out.println("surname:");
String s = in.nextLine();
System.out.println(n + s);
break;
}
Output:
select:
1
first name:
surname:
The nextLine method is ignored because there is a newline character left in the nextInt method. There are two ways to fix this problem.
Solution 1:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = in.nextInt();
in.nextLine();
Solution 2:
Scanner in = new Scanner(System.in);
System.out.println("select:");
int select = Integer.parseInt(in.nextLine());
Replacing Scanner with BufferedReader and InputStreamReader could fix it, try:
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("select:");
int select = Integer.parseInt(input.readLine());
switch (select) {
case 1:
System.out.println("first name:");
String n = Integer.parseInt(input.readLine());
System.out.println("surname:");
String s = Integer.parseInt(input.readLine());
System.out.println(n + s);
break;
}

java - trying to catch exception from scanner in a loop [duplicate]

I'm trying to make a small program more robust and I need some help with that.
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
System.out.print("Enter number 1: ");
num1 = kb.nextInt();
while(num2 < num1) {
System.out.print("Enter number 2: ");
num2 = kb.nextInt();
}
Number 2 has to be greater than number 1
Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r instead of a number the program just exits.
Use Scanner.hasNextInt():
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Here's a snippet to illustrate:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
You don't have to parseInt or worry about NumberFormatException. Note that since the hasNextXXX methods don't advance past any input, you may have to call next() if you want to skip past the "garbage", as shown above.
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.
This should work:
import java.util.Scanner;
public class Test {
public static void main(String... args) throws Throwable {
Scanner kb = new Scanner(System.in);
int num1;
System.out.print("Enter number 1: ");
while (true)
try {
num1 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
int num2;
do {
System.out.print("Enter number 2: ");
while (true)
try {
num2 = Integer.parseInt(kb.nextLine());
break;
} catch (NumberFormatException nfe) {
System.out.print("Try again: ");
}
} while (num2 < num1);
}
}
Try this:
public static void main(String[] args)
{
Pattern p = Pattern.compile("^\\d+$");
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
String temp;
Matcher numberMatcher;
System.out.print("Enter number 1: ");
try
{
num1 = kb.nextInt();
}
catch (java.util.InputMismatchException e)
{
System.out.println("Invalid Input");
//
return;
}
while(num2<num1)
{
System.out.print("Enter number 2: ");
temp = kb.next();
numberMatcher = p.matcher(temp);
if (numberMatcher.matches())
{
num2 = Integer.parseInt(temp);
}
else
{
System.out.println("Invalid Number");
}
}
}
You could try to parse the string into an int as well, but usually people try to avoid throwing exceptions.
What I have done is that I have defined a regular expression that defines a number, \d means a numeric digit. The + sign means that there has to be one or more numeric digits. The extra \ in front of the \d is because in java, the \ is a special character, so it has to be escaped.
I see that Character.isDigit perfectly suits the need, since the input will be just one symbol.
Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
reader.read();
}
catch(Exception e) {
e.printStackTrace();
}
reader.close();
What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.
I think that's correct, if you don't want to deal with the exceptions.

Need to close out java with the letter q

I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException

How to loop user input until an integer is inputted?

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

Categories