Java exception handling - java

so I'm kind of new to catching errors and such. Anyways, the program is supposed to ask the user for 2 integers and then add them together. Simple, but if either of the numbers are not integers, than an error is thrown. Currently, if I enter 2 integers, instead of adding them, it just restarts the getAnswer() method and outputs them again. Also, if you enter more than one error, it will simply exit.
package javaapplication1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Intro();
System.out.println("Your answer: "+getAnswer());
}
private static void Intro() {
System.out.println("Hello this program adds 2 integers together and catches errors.");
getAnswer();
}
private static int getAnswer() throws InputMismatchException {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown");
return 0;
}
}
}

You are calling getAnswer(); totally two times, so you just remove the call from Intro() method which will solve the problem.
private static void Intro() {
System.out.println("Hello this program adds 2
integers together and catches errors.");
}
If you want to prompt the user to reenter the input again, you can call the getAnswer() in the catch block as shown below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Please input a number");
int num1 = scanner.nextInt();
System.out.println("Please input a second number");
int num2 = scanner.nextInt();
return num1+ num2;
} catch (InputMismatchException exp) {
System.out.println("Exception thrown, please reenter values:");
getAnswer();
}
return 0;
}
One more point is that rather than catching the InputMismatchException, the other better way is read the inputs as strings and validate that they contain only numeric values like below:
private static int getAnswer() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please input a number");
String num1 = scanner.nextLine();
System.out.println("Please input a second number");
String num2 = scanner.nextLine();
if(num1.matches("[0-9]+") && num2.matches("[0-9]+")) {
return Integer.parseInt(num1)+ Integer.parseInt(num2);
} else {
System.out.println(" Your inputs contain Invalid characters");
getAnswer();
}
return 0;
}

Related

InputMismatchException help, how to override?

So, I've been stuck on this problem for a while and do not understand why my code is not working. I'm trying to teach myself Java and looking at conditionals and loops right now. So the program basically is just trying to read in an integer (int num), but if anything besides an int is entered have it ask for correct input and give a message describing what has been entered. I hope that makes sense. I'm not entirely sure if this is correct but I'm also very new to this and have been struggling to figure out what I'm missing.
Here's the code:
import java.util.Scanner;
public class LoopPrac{
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
int num;
boolean bool = false;
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
while(bool = false){
System.out.println("Enter an Integer: ");
num = scan.nextInt();
scan.nextLine();
if(scan.hasNextDouble()){
System.out.println("Error: Index is Double not Integer.");
}
if(scan.hasNext()){
System.out.println("Error: Index is String not Integer.");
}
if(scan.hasNextInt()){
bool = true;
}
}
System.out.println(num);
}
}
Your exception InputMismatchException is because you ask the scanner to scan the next integer scan.nextInt() but it found double or string or something else so it throws an exception that this input is not a integer.
So you can fix your code by first ask the scanner is next input is integer or not scan.hasNextInt(), it it int scan it, else check if it double or any type to print error message
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an Integer: ");
if (scan.hasNextInt()) {
int Index = scan.nextInt();
System.out.println("Index = " + Index);
}
else if (scan.hasNextDouble()) {
System.out.println("Error: Index is Double not Integer.");
}
else {
System.out.println("Error: Index is not Integer.");
}
}

How to stop program from crashing?

I want the program to not crash when the user inputs anything other than a number. For example, if someone enters random letters, it should display a message saying, "input not valid, please enter a valid integer". Then prompting them if they would want to continue or not.
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("outDataFile.txt"));
Scanner input=new Scanner(System.in);
int choice = 0;
String repeat;
//Loop repeats program until user quits
do
{
//Loop repeats until a valid input is found
do
{
//Asks for number and reads value
System.out.print("\nEnter an integer and press <Enter> ");
choice = input.nextInt();
//Prints error if invalid number
if(choice <= 0)
System.out.println("Invalid Input.");
There are multiple ways to achieve that:
First is to catch the exception thrown by the Scanner and flag the loop to carry on when an exception is caught. This is not a good practise since the exception thrown by the Scanner, InputMismatchException, is an unchecked exception. Meaning the cause of this exception can be easily caught by an if/else statement.
In your case, you should try to receive the input as a String, then validate the input if it looks like a number:
Loop per character approach:
String string = scanner.nextLine();
for (int i = 0; i < string; i++) {
char ch = string.charAt(i);
if (!Character.isDigit(ch)) {
System.out.println("Input is not a number");
break; // stop the for-loop
}
}
int input = Integer.parseInt(string);
RegEx approach:
String numericRegex = "[0-9]+";
String string = scanner.nextLine();
if (!string.matches(numericRegex)) {
System.out.println("Input is not a number");
}
int input = Integer.parseInt(string);
These are popular approach to your problem, it is now up to you on how will you control your loops to repeat when an invalid input is encountered.
Use a simple try catch that will catch and a simple recursive method as such:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println(getUserInput());
}
private static int getUserInput()
{
int choice = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a value");
try
{
choice = input.nextInt();
} catch (InputMismatchException exception)
{
System.out.println("Invalid input. Please enter a numeric value");
getUserInput();
}
return choice;
}
}

Java, How to break a loop when input is empty? [duplicate]

This question already has answers here:
How to test for blank line with Java Scanner?
(5 answers)
Closed 3 years ago.
The goal of this is to let the user enter a number per line and when the user no longer wish to continue they should be able to enter a empty line and when that happens the program should you give you a message with the largest number.
Problem is I can't make the loop break with an empty line. I'm not sure how to. I've checked other questions for a solution but I couldn't find anything that helped. I also can't assign scan.hasNextInt() == null....
I'm sure there is a quick and logical solution to this that I'm not thinking of.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
while(scan.hasNextInt()){
int n = scan.nextInt();
if (n > x){
x = n;
}
}
System.out.println("Largets number entered: " + x);
}
}
This should solve your problem:
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.(empty line)");
int x = 0;
try {
while(!scan.nextLine().isEmpty()){
int num = Integer.parseInt(scan.nextLine());
if(num > x) {
x = num;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Largest number entered: " + x);
scan.close();
}
}
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number and press [Enter] per line, when you no longer wish to continue press [Enter] with no input.");
String str = scanner.nextLine();
int x = 0;
try {
while(!str.isEmpty()){
int number = Integer.parseInt(str);
if (number > x){
x = number;
}
str = scanner.nextLine();
}
}
catch (NumberFormatException e) {
System.out.println("There was an exception. You entered a data type other than Integer");
}
System.out.println("Largets number entered: " + x);
}
}

Exceptions handling

I want it allow the user to enter in two int after the incorrect input. I tried continue; in the catch block, but it only threw run-time errors. I just want it to go back to the top of the main method after the throwing the error. See how in the pic it didn't allow the user to input any numbers. I want to fix that part.
Here's the code. This is only for practice.
/**
practing exceptions, example 1 in book for exceptions
*/
import java.util.Scanner;
public class PracticeExceptions extends Exception {
public static void main(String[] args)
{
String response = "y";
Scanner keyboard = new Scanner(System.in);
do{
int n1, n2;
double r;
System.out.println("Please enter two numbers");
try{
n1 = keyboard.nextInt();
n2 = keyboard.nextInt();
r = (double) n1/n2;
System.out.format("Your answer: %.2f %n", r);
}catch(Exception a){
System.out.println("Invaild input please try again");
}
System.out.println("Again (y/n)");
response = keyboard.next();
}while(response.equalsIgnoreCase("y"));
}
}
Get rid of the invalid input in you scanner buffer
}catch(Exception a){
System.out.println("Invalid input please try again");
keyboard.next();
}
The code will now drop down to System.out.println("Again (y/n)");
If you want to loop back to the top add a continue after keyboard.next();

Prevent input error

import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}

Categories

Resources