at this program once the exception is caught, the program displays the catch message and program terminates successfully by itself (I need to run the program again manually if want to ask the user input). I dont want the program to finish but automatically it should ask the user to enter a valid number and performs the functions from the beginning, how to write for this?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a Whole Number to divide: ");
int x = sc.nextInt();
System.out.println("Enter a Whole number to divide by: ");
int y = sc.nextInt();
int z = x / y;
System.out.println("Result is: " + z);
}
catch (Exception e) {
System.out.println("Input a valid number");
}
finally{
sc.close();
}
}
}
Output
Enter a Whole Number to divide:
5
Enter a Whole number to divide by:
a
Input a valid number
Process finished with exit code 0
There are some issues with nextInt that you need to be careful about, You can check out this link: Scanner is skipping nextLine() after using next() or nextFoo()?.
For your program, use a while loop, and you need to be aware of Y could be 0, which would cause an ArithmeticException.
while (true) {
try {
System.out.println("Enter a Whole Number to divide: ");
// use nextLine instead of nextInt
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter a Whole number to divide by: ");
int y = Integer.parseInt(sc.nextLine());
if (y == 0) {
System.out.println("divisor can not be 0");
continue;
}
double z = ((double) x) / y
System.out.println("Result is: " + z);
break;
}
catch (Exception e) {
System.out.println("Input a valid number");
}
}
sc.close();
Related
I wanted to print the multiplication table of a number. So I made a while(true) block to ontinously take inputs from the user. I also made a try and catch block, so that I could handle the exeptions.
Here is my code below :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Getting the multiplication table of any number");
while (true) {
try {
System.out.println();
System.out.print("Enter a number: ");
long number = scanner.nextLong();
for (byte num = 1; num < 11; num++) {
System.out.println(number + "X" + num + " = " + (number * num));
}
System.out.println();
System.out.println();
} catch (Exception e) {
System.out.println("Please enter a valid input.");
}
}
}
}
When I run the programm, it run fine till I introduce just one error. Then it just gives the output:
Enter a number: Please enter a valid input.
Both the statements on the same line, And just continuosly prints the line without any delay or without letting me give it an input.
Why is this happening and how can I correct it?
You can change your catch block as:
catch (Exception e) {
System.out.println("Please enter a valid input.");
scanner.next();
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
Hello everybody!
I just started java and I learned about control flow and now I moved on to user input, so I don't know much. The problem is this code. Works just fine if you enter valid input as I tested, nothing to get worried about. The problem is that I want to check for wrong input from user, for example when they enter a string like "asdew". I want to display the error from else statement and to move on back to asking the user for another input, but after such an input the program will enter in an infinite loop displaying "Enter the number X: Invalid input. Please, enter a number.".
Can you tell me what's wrong? Please, mind the fact that I have few notions when it comes to what java can offer, so your range of solutions it's a little bit limited.
Call userInput.nextLine(); just after while:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...
The issue is, that once you enter intput, which can not be interpreted as an int, userInput.hasNextInt() will return false (as expected). But this call will not clear the input, so for every loop iteration the condition doesn't change. So you get an infinite loop.
From 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.
The fix is to clear the input if you came across invalid input. For example:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
Another approach you could take, which requires less input reads from the scanner, is to always take the next line regardless and then handle the incorrect input while parsing.
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
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);
}
}
T student
Im wondering if the user input a Character not an integer.How can i Show the word INVALID to him
and let him Type again.
EXAMPLE:
input a two number
a
INVALID try Again:1
2
Sum of two number=3
public static void main(String[] args) {
int x = 0, y, z;
System.out.println("Enter two integers to calculate their sum");
Scanner in = new Scanner(System.in);
try {
x = in.nextInt();
} catch (InputMismatchException e ) {
System.out.print("INVALID");
}
y = in.nextInt();
z = x + y;
System.out.println("Sum of the integers = " + z);
}
You can do for example:
while(true) {
try {
x = in.nextInt();
break;
} catch (InputMismatchException e ) {
System.out.print("INVALID try again:");
in.next(); //To wait for next value otherwise infinite loop
}
}
Basically you need to add the input into a loop and keep looping until you get valid input. You can write it in different ways but that should be the idea.
The in.next() in the catch is required because nextInt() doesn't consume the new line character of the first input and this way we skip to that.
If I were you I would use in.nextLine() for each line of parameters and the manipulate the String that I get to check for valid input instead of waiting for exception.
Requirement:
Accept 10 numbers, input them into an array and then invoke a method to calculate and return the smallest. This program is suppose to be error proof so when a user enters an invalid entry, it notifies the user and reprompts. I am trying to use try catch but when an invalid entry is entered, ie a character, the scanner won't reprompt.
Any ideas?
Tried:
//Variables
double [] doubleArray = new double[10];
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("This program will prompt for 10 numbers and display the smallest of the group");
//Get values
for (int i = 0; i < doubleArray.length; i++) {
try {
System.out.println("Please enter entry "+ (i+1));
doubleArray[i] = input.nextDouble();
} catch (InputMismatchException e) {
// TODO: handle exception
System.out.println("Please enter a rational number");
i--;
}
}
//Invoke method and display result
System.out.println("The smallest value is: "+index(doubleArray));
I don't see any call to input.nextLine(), which means nothing is ever consuming the \n entered by the user. There's a good example on scanner.nextLine usage here. If you add a call to it in your catch block, you should be all set.
Try calling input.nextLine(); in your catch. Then the \n will be taken from the input which let's you enter the next new number.
for(int i = 0; i < doubleArray.length; ++i) {
try {
doubleArray[i] = input.nextDouble();
} catch(Exception e) {
input.nextLine();
--i;
}
}
Try something like (and make sure you consume the whole line unless you want to allow multiple numbers to be input on the same line
boolean validEntry = false;
System.out.println("Enter a rational number: ");
while (!validEnry) {
try {
double value = input.nextDouble();
validEntry = true;
doubleArray[i] = value;
} catch (Exception e) {
System.out.println("Entry invalid, please enter a rational number");
}
}
...
You have to discard the false inputted data, add input.nextLine() in the catch block.