This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 6 years ago.
I'm making simple program where the user inputs a class number of a student(cn) and the grade of that student(ngrade). I was trying to add an exception that checks if the input of the cn and ngrade are integers. If not the user will be informed that it is invalid and asks to re enter the details.
problem: i did use while loop to check the inputs throughout the loop. but i'm getting a infinite loop.
CODE:
import java.io.*;
import java.util.*;
public class trrying {
public static void main(String[] args) {
int ngrade;
int cn;
int A = 0, B = 0, C = 0, D = 0, E = 0;
boolean test = false;
Scanner sn = new Scanner(System.in);
while (!test) {
try {
for (int i = 0; i <= 2; i++) {
System.out.println("Enter class number: ");
cn = sn.nextInt();
System.out.println("Enter numeric grade: ");
ngrade = sn.nextInt();
System.out.println("Letter Grade: ");
if (ngrade >= 90) {
A++;
System.out.println("A");
} else {
System.out.println("HELLO");
}
test = true;
}
test = false;
} catch (Exception e) {
System.out.println("ERROR! ");
// System.out.println("Enter class number: ");
}
}
}
}
One option to get the behavior you want would be to read in each input as a string, using Scanner#nextLine(), and then manually try to parse that input as an integer. If successful, accept that input and continue with your logic. If not successful, then catch the exception, and repeat the loop to get another user input.
for (int i=0; i <= 2; i++) {
String line = "";
while (true) {
System.out.println("Enter class number: ");
line = sn.nextLine();
try {
cn = Integer.parseInt(line);
break;
} catch(Exception e) {
System.out.println("Enter class number as an integer only.");
}
}
while (true) {
System.out.println("Enter numeric grade: ");
line = sn.nextLine();
try {
ngrade = Integer.parseInt(line);
break;
} catch(Exception e) {
System.out.println("Enter numeric grade as an integer only.");
}
}
System.out.println("Letter Grade: ");
if (ngrade >= 90) {
System.out.println("A");
}
else {
System.out.println("HELLO");
}
test = true;
}
Related
I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}
I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}
I have this method and it works fine. I need to put a try/catch statement so
the method can continue if the user puts in a letter. I don't know where to put the statement, It seems everywhere I put it it get's wrong. Could somebody please show me where to put this statement?
public void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
number = in.nextInt();
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}
if (!end) {
System.out.println("I cant find number " + number
+ " in the array, please try again ");
}
}
}
Your for loop I can't explain, you need only check values between 0 and 20,
And when you call try catch, you have to skip loop after exception
public static void myMethod() {
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number=0;
boolean end = false;
while (!end) {
System.out.println("Please give an number between 0-20: ");
//check symbol
try{
number = Integer.valueOf(in.next());
}catch(Exception e)
{
System.out.println("It's not a number! ");
continue; //skip loop
}
if((number>=0)&&(number<=20))
{
System.out.println(array[number]);
end=true;
}
else
System.out.println("I cant find number " + number
+ " in the array, please try again ");
/* why do you use loop here???
* u need to check if number between 0-20
for (int i = 1; i < array.length; i++) {
if (i == number) {
System.out.println(array[number]);
end = true;
}
}*/
}
}
public static void main(String[] args) {
Test test = new Test();
Scanner in = new Scanner(System.in);
int array[] = new int[21];
int number;
System.out.println("Please give an number between 0-20: ");
do{
try{
number = Integer.parseInt(in.next());
}
catch(Exception e){
System.out.println("Please give an number between 0-20: ");
number = -1;
}
}
while(!(number <= 20 && number >=0 ));
System.out.println(array[number]);
}
System.out.println("Please give an number between 0-20: ");
try{
number = in.nextInt();
}catch(Exception e){
number = 1; //Put random number of default number here
}
I made this java code to input a number:
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("enter number ");
temp = scan.nextInt();
if(temp >= 5 && temp <= 40){
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("|");
}
out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++) {
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}else{
out.print("enter a number between 5 and 40");
}
}while(temp != 0);
}
}
However, this will return an error if I enter for example a letter or an invalid character. I would like to know how to, instead of making the program crash, make it display an error message and then asking again the question until the entry is correct?
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int temp=0;
boolean error=false;
do{
error=false;
try
{
Scanner scan = new Scanner(System.in);
System.out.print("enter number ");
temp = scan.nextInt();
if(temp==0)
break;
if(temp >= 5 && temp <= 40)
{
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("|");
}
System.out.println();
y--;
z+=2;
}
for(int c = 0; c < 1 + temp/10; c++)
{
for (int i = 0; i <= x / 2; i++)
{
System.out.print(" ");
}
System.out.println("|");
}
}
else
{
System.out.println("enter a number between 5 and 40");
}
}catch(Exception e)
{
System.out.println("Enter a valid number..try again");
error=true;
}
}while(temp != 0 || error);
}
}
When the error or exception occurs i.e. in scan.nextInt() an Exception is thrown and as you have not caught the exception the JVM stops executing the program.
So always write statements which can throw Exceptions within a try{ } block and immediately follow it with a catch(Exception e) {} block to catch the exception. If no exception occurs then catch block will not execute. If any error occurs inside try{} block : control jumps to catch block and it is executed and all other statements in try{} (after the erroneous line) are ignored.
try
{
..
error
.. // skipped
..
}
catch(Exception e)
{
...
...// handle exception
}
// control comes here after executing catch block
Read in the value from the user as a string and then try to parse it to a number in a try {} catch{} block, if an exception is thrown parsing it, tell the user only numbers are acceptable. if not continue processing with the number they gave you.
The Scanner has a method to check if the next token is an integer: hasNextInt.
You could do this:
package com.sandbox;
import java.util.Scanner;
public class Sandbox {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer:");
while (!scanner.hasNextInt()) {
System.err.println("Wrong! Enter an integer");
scanner.next();
}
System.out.println("Your integer was: " + scanner.nextInt());
}
}
This worked as you'd want on a windows console. I'm a little concerned it'll work incorrectly on Linux/Mac. Anyone mind testing it out for me? If this works, I like it best because there's no try/catch.
Extending from #Shouvik Roy's answer..
import java.util.Scanner;
public class Bingo {
public static void main(String[] args){
boolean isInt = false;
int temp;
System.out.print("enter a number ");
do{
Scanner scan = new Scanner(System.in);
try
{
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt);
}
}
------------------Edit-------------------
boolean isInt = false;
System.out.print("enter a number ");
do{
try
{
Scanner scan = new Scanner(in);
temp = scan.nextInt();
isInt = true;
}
catch(Exception e)
{
System.out.println("Couldn't read number. Reason - "+e.getMessage());
System.out.println("Enter a valid number ");
}
}while(!isInt)
I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}