How do I prompt a user until they enter a valid integer? - java

Valid integer being a letter. I don't know the command to make it check the strings, nor do I know where to find it. Any help would be appreciated.
import java.util.Scanner;
public class Stringtest{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int test = 10;
while (test>0){
System.out.println("Input the maximum temperature.");
String maxTemp = input.nextLine();
System.out.println("Input the minimum temperature.");
String minTemp = input.nextLine();
}
}
}

Use the nextInt() to get the next integer value.
You should try/catch it in case user types a non-integer value.
Here's an example:
Scanner input = new Scanner(System.in);
// infinite loop
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
// TODO whatever you need to do with max temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
// TODO whatever you need to do with min temp
}
catch (Throwable t) {
// TODO handle better
t.printStackTrace();
break;
}
}

Just use input.nextInt(), and then a simple try-catch for an invalid int value.
You shouldn't try to save temperature indexes as Strings either.

You should use Integer.parseInt i.e User can enter any String and then you can check if it is an integer using this api, if it is not integer you will get an exception and then you can for another entry from user. Check below link for usage.
http://www.tutorialspoint.com/java/number_parseint.htm

try{
int num = Integer.parseInt(str);
// is an integer!
} catch (NumberFormatException e) {
// not an integer!
}

Maybe you can do something like this:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf("\"%s\" is not a valid number.\n", input);
}
number = scanner.nextInt();
} while (number < 0);

Related

NumberFormatException not wrking java

I'm new to this I can't figure it out how to break the loop.
`````````` Java```````````
public static void main(String[] args) {
Scanner input= new Scanner (System.in) ;
System.out.println("Enter number list:");
try {
String data = input.nextLine();
ArrayList<Integer> myArray = new ArrayList<Integer>();
int num;
while (true){
num = Integer.parseInt(data);
myArray.add(num);}
}
catch (NumberFormatException e) {
e.printStackTrace();}
You should read new inputs inside your loop:
try {
...
while (true) {
num = Integer.parseInt(data);
myArray.add(num);
}
}
catch (NumberFormatException e) {
};
Currently you are adding the same input infinite times to your List.
P.S. perhaps you shouldn't use an infinite while loop. How do you plan to finish reading the inputs? By catching a NumberFormatException when the user enters an invalid number? It's not a good practice to use exceptions as part of your logic.
Thank you got it to work
while(true) {
Scanner input= new Scanner (System.in) ;
System.out.println("Please enter a number or anything else to stop:");
String data = input.nextLine();
int num;
try{
num = Integer.parseInt(data);
myArray.add(num);
int arraySize;
arraySize = myArray.size();
Collections.sort(myArray);
} catch (NumberFormatException e) {
break;
}
}
}

Ask to insert numbers only

So I'm trying to make a simple calculator.
How do I make when I enter the first number, it works but if I insert "abc" it will give me an error.
How I make it in order when you write "abc" to say " please enter a number "
import java.util.Scanner;
public class calculator
{
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if ( c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
}
}
You can verify the input until be a int using a scanner property Scanner.hasNextInt()
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!scanner.hasNextInt()) scanner.next();
Example:
public static void main(String[] args0) {
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
System.out.println("Insert a number ");
while (!test .hasNextInt()) test .next(); // Scanner Validation
int x = test .nextInt();
}
JavaDoc of Scanner
The error you get is an exception. You can actually "catch" your exceptions, so that when they appear, your program doesn't break, and you can do what is in place for that error (output a "Please, insert only numeric values" feedback?)
You can find some info on try-catch blocks here try-catch blocks
Try this:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner test = new Scanner(System.in);
int x;
int y;
String c;
try {
System.out.println("Insert a number ");
x = test.nextInt();
System.out.println("insert a value e.g * / + -");
c = test.next();
System.out.println("Insert another number");
y = test.nextInt();
if (c.equals("*")) {
System.out.println("the total is " + x*y);
}
if (c.equals("+")) {
System.out.println("the total is " + (x+y));
}
if (c.equals("-")) {
System.out.println("the total is "+ (x-y));
}
if (c.equals("/")) {
System.out.println("the total is "+ (x/y));
}
} catch(InputMismatchException e) {
System.out.println("Please enter correct values.");
}
}
Modifications:
The error you are getting is known as RunTime Error or Exceptions due to wrong input type. In order to handle RunTime Exceptions, You need to use try and catch block.
try and catch blocks are used to handle RunTime Exceptions. If any error or exception occurs within try block then It will be thrown to catch block to be handled instead of terminating your program.
Try this:
boolean success = false;
while (!success) {
try {
y = test.nextInt();
success = true;
} catch (InputMismatchException e) {
test.nextLine();
System.out.println("Please enter a number.");
}
}
If you're willing to accept doubles instead of ints, java doubles have a built in method isNaN(), where NaN stands for Not a Number.
if (Double.isNaN(doubleValue)) {
...
}

Ask user to input a double instead of a String without making the program shutdown

Hy, I wrote this piece of code where I'm asking the user to input a number:
public static double[] getscores()
{
int numscores=8;
double score[] = new double[numscores];
for (int a=0;a<numscores;a++)
{
Scanner ip=new Scanner(System.in);
System.out.println("Enter a score");
score[a]=ip.nextDouble();
}
return score;
}
In the eventuality where the user accidentally enters a String, how am I supposed to tell him to input a number without making the program shut down? Thanks You
You should catch the exception thrown when the user doesn't input a double, ask the user to try again, and keep looping there until the user inputs a double. Alternatively, you can use while(true) and a break statement instea of a do { ... } while. Perhaps that is a bit shorter, but this is more readable.
Use a BufferedReader instead, because Scanner does not consume the input if it fails to parse it, so you'll get stuck in an infinite loop.
public static double[] getScores() throws IOException {
final int NUM_SCORES = 8;
double[] score = new double[NUM_SCORES];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < NUM_SCORES; i++) {
System.out.println("Enter a score:");
boolean isDouble = false;
do {
try {
score[i] = Double.parseDouble(br.readLine());
isDouble = true;
} catch (NumberFormatException e) {
System.out.println("You didn't enter a double. Please try again!");
}
} while (!isDouble);
}
br.close();
return score;
}
The user is always entering a String; Scanner#nextDouble() is a convenience method to interpret String input as a double.
Write a method that keeps reading input until a double is entered:
static double readDouble(Scanner scanner) {
double score;
while (true) {
System.out.println("Enter a score");
String input = scanner.nextLine();
try {
score = Double.parseDouble(input);
break;
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid score");
}
}
return score;
}
then call it from your loop:
score[a] = readDouble(ip);
A quick but "dirty" solution would be by using try-catch:
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
try{
score[a] = ip.nextDouble();
} catch(InputMismatchException ime) {
System.out.println("Wrong input");
a--;
}
}
return score;
}

how to check whether the input is integer or not

I a making a program that will ask an int input from user and check whether user input is an integer or not. If no the program asks for an input tile it gets a integer.
Scanner in = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
int num;
if (in.hasNextInt()){
num =in.nextInt();
if(num % 2 == 0){
System.out.print("this is even!!");
} else{
System.out.println("this is odd!!");
}
} else {
System.out.print("pleas enter an integer only!!!");
num = in.nextInt();
if(num % 2 == 0){
System.out.print("this is even second check!!");
} else{
System.out.println("this is odd second check!!");
}
}
here is the code but i have some mistakes in there. it brings an error when input is not an int. pleas help with this, thanks in advance!
Try the below code, it will end only if its a valid Integer otherwise it will keep asking for Integer and I think you are looking for the same.
public void checkInt() {
Scanner scanner = new Scanner(System.in);
System.out.println("Eneter a nuber here:");
try {
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.print("this is even!!");
} else {
System.out.println("this is odd!!");
}
} catch (InputMismatchException e) {
System.out.println("pleas enter an integer only!!!");
checkInt();
}
}
You must read user input as String. Then, inside a try/catch block, make a casting to integer (Integer.parseInt()), if throws a exception is because is not a number.
May be a stupid way but this can solve your problem:
String x;
x = "5";//or get it from user
int y;
try{
y = Integer.parseInt(x);
System.out.println("INTEGER");
}catch(NumberFormatException ex){
System.out.println("NOT INTEGER");
}
Edited:
The program will try to convert the string to integer. If it is integer it will succeed else it will get exception and be caught.
Another way is to check the ASCII value.
To continue till integer is encountered:
String x;
Scanner sc = new Scanner(System.in);
boolean notOk;
do{
x = sc.next();
notOk = check(x);
}while(notOk);
System.out.println("Integer found");
}
private static boolean check(String x){
int y;
try{
y = Integer.parseInt(x);
return false;
}catch(NumberFormatException ex){
return true;
}
}
import java.util.Scanner;
public class Test {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
if(sc.hasNextInt())
System.out.println("Input is of int type");
else
System.out.println("This is something else");
}
}

How to implement int validation, so the input can only be an int and between a min and max?

I'm wondering how do I go about validating this code so the input can only be an int and between a min and max? So far I can only stop the input being less than 1 and whatever maximum is used. But I cant seem to create a scenario where if the user inputs anything other than between the max and min (e.g. "AAA") it loops. I keep getting an Input Mismatch error. Any help would be greatly appreciated!
private static int getUserOption(String prompt, int max) {
int h;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
h=sc.nextInt();
if(!sc.hasNextInt()) {
System.out.println("Invalid option. Try again!:");
}
} while(h<1 || h>max);
return h;
}
The loop is breaking because the nextInt() method is throwing an exception, which terminates the method early.
One option would be to use a try / catch block to trap the exception:
private static int getUserOption(String prompt, int max) {
int h = 0;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
try {
h=sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid option. Try again!:");
}
}while(h<1 || h>max);
return h;
}
You Can try this Code !
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a valid number: ");
while (!sc.hasNextInt()) {
System.out.println("Error. Please enter a valid number: ");
sc.next();
}
number = sc.nextInt();
} while (!checkChoice(number));
private static boolean checkChoice(int choice){
if (choice <MIN || choice > MAX) { //Where MIN = 0 and MAX = 20
System.out.print("Error. ");
return false;
}
return true;
}
Ref. Validating input with while loop and scanner
a few points:
1. to check if the input is less than a min value just add int min to the method signature.
2. to check if input is an int, catch InputMismatchException.
The revised code would be:
private static int getUserOption(String prompt, int max, int min) {
int h;
do {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
try {
h=sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid option. Try again!:");
}
} while(h<min || h>max);
return h;
}
I couldn't understand if you want to keep asking until the user types a valid answer or just ask once. The while block suggests to keep asking until is a valid input.
Here is a small snippet that what you request. I suggest that you read some books, there a plenty of suggestions at SO.
public static class InvalidUserException extends Exception {
public InvalidUserException(String message) {
super(message);
}
public InvalidUserException(String message, Throwable cause) {
super(message, cause);
}
}
private static int getIntFromScanner(int max) throws InvalidUserException {
int nextInt = 0;
Scanner sc = new Scanner(System.in);
try {
nextInt = sc.nextInt();
} catch (InputMismatchException e) {
throw new InvalidUserException("Input must be a valid Integer", e);
}
if (nextInt > max) {
throw new InvalidUserException(
"Input is bigger than allowed! Max: " + max + " Input: "
+ nextInt);
}
return nextInt;
}
public static int getUserOption(String prompt, int max) {
System.out.println(prompt);
do {
try {
return getIntFromScanner(max);
} catch (InvalidUserException e) {
System.out.println("Invalid option. Try again ("
+ e.getMessage() + ")");
}
} while (true);
}
public static void main(String[] args) {
int userOption = getUserOption("Gimme less than or equal 6!", 6);
System.out.println("You gave me " + userOption);
}

Categories