This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 2 years ago.
I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args){
number();
}
public static int number() {
System.out.print("Enter a number: ");
Scanner readLine = new Scanner(System.in);
boolean isInteger = false;
while (!isInteger) {
try {
int numbers = readLine.nextInt();
System.out.println(numbers);
isInteger = true;
} catch (InputMismatchException e) {
System.err.println("Not a valid input. Error :" + e.getMessage());
}
}
return 0;
}
}
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
if (sc.hasNextInt()) {
int number = sc.nextInt();
System.out.println(number);
} else {
System.err.println("Not a valid input. Error :" + sc.next());
}
}
Related
I'm trying to create a loop by entering the number to be added and then blocking the loop with a "exit" input from the user..but it's not working properly.
import java.util.Scanner;
public class main {
public static void main(String[] args)
{
int i,n=0,s=0;
double avg;
{
System.out.println("Input the numbers : ");
}
for (i=0;i<100;i++)
{
String input = new java.util.Scanner(System.in).nextLine ();
if(input.equals("exit")){
break;
}
Scanner in = new Scanner(System.in);
n = in.nextInt();
s +=n;
}
System.out.println("The sum of numbers is : " +s);
}
}
You have a couple of problems. One (minor) is that you are creating two scanners. Another (medium) is that your loop is set up to only go up to 100 - this is a magic number, and there's no reason to put in this artificial constraint. But your biggest problem is that you are ignoring the first entry in the loop if it is a number and not 'exit'
{
int i,n=0,s=0;
double avg;
boolean adding = true;
System.out.println("Input the numbers : ");
Scanner sc = new java.util.Scanner(System.in);
while(adding)
{
String input = sc.nextLine ();
if(input.equals("exit")){ // should proably be "EXIT" or equalsIgnoreCase
adding = false;
} else {
try {
int val = Integer.parseInt(input);
s += val;
} catch (NumberFormatException nfe) {
System.err.println ("expecting EXIT or an integer");
}
}
}
System.out.println("The sum of numbers is : " +s);
}
After this line your console does not have any next line or entry to read.
String input = new java.util.Scanner(System.in).nextLine ();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to solve the next task:
1. Asking the user for a positive integer.
2. If the user adds a negative or a real number or both, the next error message should be displayed on the console: "wrong input".
That is what I have done so far.
Scanner sc = new Scanner(System.in);
System.out.print("Please, add a positive integer! ");
int num = sc.nextInt();
if (num < 0) {
System.out.println("wrong input");
}
Everything works well, except I cannot make sure that the user receives the error message if he/she doesn't type an integer but a real number. In this case, the program goes wrong.
I would appreciate the help.
import java.util.Scanner;
import java.util.InputMismatchException;
public class ScanTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean badInput = true;
int num;
// Keep asking for input in a loop until valid input is received
while(badInput)
{
System.out.print("Please, add a positive integer! ");
try {
num = Integer.parseInt(sc.nextLine());
// the try catch means that nothing below this line will run if the exception is encountered
// control flow will move immediately to the catch block
if (num < 0) {
System.out.println("Please input a positive value.");
} else {
// The input is good, so we can set a flag that allows us to exit the loop
badInput = false;
}
}
catch(InputMismatchException e) {
System.out.println("Please input an integer.");
}
catch(NumberFormatException e) {
System.out.println("Please input an integer.");
}
}
}
}
Occasionally I find it easier to read in a string and then try and parse it. This presumes you would like to repeat the prompt until you get a valid number.
Scanner sc = new Scanner(System.in);
int num = -1;
while (num < 0) {
System.out.print("Please, add a positive integer! ");
String str = sc.nextLine();
try {
num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Only integers are accepted.");
continue;
}
if (num < 0) {
System.out.println("Input is < 0.");
}
}
Read about NumberFormatException here.
When you're using Scanner.nextInt() the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException. To make sure invalid input doesn't stop your program, use a try/catch to handle the exception:
int num;
try {
num = sc.nextInt();
// Continue doing things with num
} catch (InputMismatchException e) {
// Tell the user the error occured
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I'm using on program that I need get input from console in java. here is a simple code only for showing you the problem.
public class Main {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string "+s);
int a = in.nextInt();
System.out.println("You entered integer "+a);
float b = in.nextFloat();
System.out.println("You entered float "+b);
System.out.println();
}
}
for input :
"stackOverFlow"
12
3.4
out put is :
You entered string stackOverFlow
You entered integer 12
and out put should be :
You entered string stackOverFlow
You entered integer 12
You entered float 3.4
what is the problem why the last line don't be read by scanner ?
Scanner does not work like this. in.nextLine() will consume the whole line and wait for you to press return, and then call the next statement, which happens to be a print. Then, it expects you to enter an int, so on...
Your program would expect input as follows:
> stackOverFlow
You entered string stackOverFlow
> 12
You entered integer 12
> 3.4
You entered float 3.4
If you want to parse a String, int, and float from the first string a user enters, that is a different operation (assuming you enter some string that would be split into 3 elements by a space):
import java.util.Scanner;
public class Test {
static int i;
static float f;
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a: string int float");
String s = in.nextLine();
String[] split = s.split(" ");
String str = split[0];
try {
i = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
try {
f = Float.parseFloat(split[2]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("String: " + str);
System.out.println("Int: " + i);
System.out.println("Float: " + f);
in.close();
}
}
How to have a try and catch statement to validate the input in variable odd is a number else print an error message? I am new in java programming. Appreciate any help
import java.util.Scanner;
public class ScenarioB{
public static void main (String[]args){
int odd;
Scanner scan = new Scanner(System.in);
System.out.print("Enter An Odd Number\n");
odd = scan.nextInt();
}
}
The Scanner class has a method for this
Scanner in = new Scanner(System.in);
int num;
if(in.hasNextInt()){
num = in.nextInt();
System.out.println("Valid number");
}else{
System.out.println("Not a valid number");
}
Output 1:
8
Valid number
Output 2:
a
Not a valid number
Your code will like bellow:
try {
int scannedNumber;
Scanner scan = new Scanner(System.in);
System.out.print("Enter An Odd Number\n");
String userInput = scan.nextLine();
System.out.println("You pressed :" + userInput);
scannedNumber = Integer.parseInt(userInput);
if (scannedNumber % 2 == 0) {
throw new Exception("Not an odd number");
}
System.out.println("You pressed odd number");
} catch (Exception e) {
System.out.println("" + e.getMessage());
}
Here after taking input as String. Then cast as integer. If casting failed then it will throw NumberFormatException. If it is a number then check is it odd? If not odd then it is also throwing an exception.
Hope this will help you.
Thanks :)
This question already has answers here:
How to read a single char from the console in Java (as the user types it)?
(7 answers)
Closed 5 years ago.
I have this following java program which is working fine without while loop, but I want to run the execution until user pressed Q key from the keyboard.
So What condition should be put in while loop which breaks the loop?
import java.awt.event.KeyEvent;
import java.util.Scanner;
import static javafx.scene.input.KeyCode.Q;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(kbhit() != Q){
System.out.print("Input first binary number: ");
try{
String n = in.nextLine();
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}
Any help would be great.
Thank You.
I don't think you can use KeyEvent within a console application as there's no keyboard listener defined.
Try a do-while loop to watch for an input of the letter q. And you should compare strings using equals method
Scanner in = new Scanner(System.in);
String n;
System.out.print("Input first binary number: ");
do {
try{
n = in.nextLine();
// break early
if (n.equalsIgnoreCase("q")) break;
System.out.println(Integer.parseInt(n,2));
}
catch(Exception e){
System.out.println("Not a binary number");
}
// Prompt again
System.out.print("Input binary number: ");
} while(!n.equalsIgnoreCase("q"));
What about this?
public class BinaryToDecimal {
public static void main(String[] args) {
System.out.print("Input first binary number: ");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
while(!"q".equalsIgnoreCase(line.trim())){
try{
System.out.println(Integer.parseInt(line,2));
System.out.print("Input next binary number: ");
line = in.nextLine();
}
catch(Exception e){
System.out.println("Not a binary number");
}
}
}
}