Enter a string to integer scanner [duplicate] - java

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I want to say enter an integer when someone trying to enter a string in this code.
Can you help me?
Here is my code:
import java.util.Scanner;
public class kl {
public static void main(String[] args) {
boolean primen = true;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a positive integer that is prime or not : ");
int ncheck = input.nextInt();
if (ncheck < 2) {
primen = false;
}
for (int i = 2; i < ncheck; i++) {
if (ncheck % i == 0) {
primen = false;
break;
}
}
if (primen == true) {
System.out.println(ncheck + " is a prime number.");
}
else {
System.out.println(ncheck + " is not a prime number.");
}
}
}

You can find your solution here: Exception handling, Or use codes below
Here is your complete code:
while(true){
System.out.print("Please enter a positive integer that is prime or not : ");
try{
int i = input.nextInt();
break;
}catch(InputMismatchException e){
System.out.print("Wrong type input, pls try again!");
input.nextLine(); \\ prevent infinite loop
}
You can see: I use a Exception handle processor to catch the InputMismatchException and print on console the message. You can replace InputMismatchException by Exception. It's largest Exception Handler class in java

There are two approaches you can use with Scanner.
Call nextInt() and then catch and handle the InputMismatchException that you will get if the next input token isn't an integer.
Call hasNextInt(). If that returns true then call nextInt().
In either case, if you expected an integer and the user entered something else, then neither nextInt() or hasNextInt() will "consume" the unexpected characters. So if you want the user to try try again, you need to call nextLine() which will read all remaining characters on the line. You will typically discard them.
For more information on handling exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
For more information on using Scanner:
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Related

How to prevent users from entering anything but int [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 4 years ago.
Im trying to create a simple program where user enters an integer and if its not an integer it prints that an error occured and the program loops until user enters an integer. I found this try-catch solution but it doesn`t work properly. If user doesnt enter an integer the program will infinitly loop.
What would the correct solution be?
Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while(isInt == false)
{
System.out.println("Enter a number:");
try
{
number = input.nextInt();
isInt = true;
}
catch (InputMismatchException error)
{
System.out.println("Error! You need to enter an integer!");
}
}
You're close.
It's easier to fail on parsing a string than it is to try to get an int from the Scanner since the scanner will block until it gets an int.
Scanner input = new Scanner(System.in);
int number;
boolean isInt = false;
while (isInt == false) {
System.out.println("Enter a number:");
try {
number = Integer.parseInt(input.nextLine());
isInt = true;
} catch (NumberFormatException error) {
System.out.println("Error! You need to enter an integer!");
}
}

InputMismatchException for String input into integer field

I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.

Java scanner adding variable conditions

I'd like to ask how do i exactly condition what my program does if my user types in a character or a string if i want him to type an integer instead? I tried to do it how i showed here in quotes and also tried with "equals". The second method didn't work the first seems to be behaving strangely the IF part works but ELSE is completely ignored.
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
int number1 = input.nextInt();// prompt
if (number1 == (char)number1){
System.out.println("Ok.");
}
else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
System.out.print("Enter second integer: ");
int number2 = input.nextInt();// prompt
int sum =(number1 + number2);
System.out.printf("Your sum is: %d%n", sum);
}
I suggest you to use the regular expression in the hasNext() function as follows to have a finer control, for example use the following pattern if you look for the numbers,
sc.hasNext("[0-9]+")
Here is the documentation for the hasNext(String pattern) function,
public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.
Here is the simple code to perform the check,
Scanner sc=new Scanner(System.in);
int input = 0;
while(true) {
System.out.println("enter a number");
if(sc.hasNext("[0-9]+")) {
input = sc.nextInt();
break;
} else {
System.out.println("not a number, try again");
sc.next(); // just consume, but ignore as its not a number
}
}
System.out.println("Entered number is : "+input);
You can use a user defined function as shown below and call it
public static boolean isNum(String input)
{
try
{
int d = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
Then you can call this method from your main function.
if(isNum(number1))
I am not sure if I understand your question, but I see this as follows:
Users will always type a sequence of characters from the input, then your program has to check if that String can be converted to Int, if it can not be converted it should prompt back to the user telling the typed data is not an int. In that case your nextInt will throw an InputMismatchException.
Probably a much more elegant solution is to use hasNextInt(10):
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
if (input.hasNextInt(10)){
System.out.println("Ok. Typed number: " + input.nextInt());
}else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
[...]
}
Try this,
try {
int number1 = sc.nextInt();// prompt
System.out.println("Ok.");
} catch (InputMismatchException ex) {
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
Scanner.nextInt(); Scans the next token of the input as an int.
Program won't execute beyond this line if input is not int.
So it will never enter else part. Don't do any int validation.
I would suggest always use try/catch block to handle incorrect input and show useful message. Also don't forget to close Scanner object.

Throw an error when a string is entered instead of an int [duplicate]

This question already has answers here:
Java input mismatch error using scanner
(3 answers)
Closed 8 years ago.
I am working on homework for my class. I have written a method to throw an error if an incorrect integer is entered and I am trying to give an error message when a string is entered instead of an int but I am not sure how. I am not allowed to use parsInt or built in string methods. I would be grateful for any help.
int playerNum = stdin.nextInt();
while (invalidInteger(playerNum) == -1 || invalidInteger(playerNum) == -2 || invalidInteger(playerNum) == -3)
{
if(invalidInteger(playerNum) == -1)
{
System.out.println("Invalid guess. Must be a positive integer.");
System.out.println("Type your guess, must be a 4-digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -2)
{
System.out.println("Invalid guess. Must be a four digit integer.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
if(invalidInteger(playerNum) == -3)
{
System.out.println("Invalid guess. Must have distinct digits.");
System.out.println("Type your guess, must be a four digit number consisting of distinct digits.");
count++;
}
playerNum = stdin.nextInt();
}
Added this snippet to catch the exception. Thanks to almas shaikh.
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Use the following code:
try {
int playerNum = scanner.nextInt();
//futher code
} catch (InputMismatchException nfe) {
System.out.println("You have entered a non numeric field value");
}
Scanner throws InputMismatchException when you enter string instead of integer. So very next time when you try to enter String it will throw the InputMismatchException exception, you could catch the exception and say you let user know that user has entered invalid input and let him retry.
Check the java doc for nextInt() -- is stdin a Scanner? If so, nextint() will throw an exception if some non-integer text is entered. You would probably want to catch that and print your own pretty error. Though, you might be going even further than the assignment expects. The phrase "throw an error if an incorrect integer is entered" might imply that only integers will be entered. It depends on the instructor/class.
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
try
{
int i = in.nextInt();
}
catch(InputMismatchException e)
{
e.printStackTrace();
}
}
}
I hope this will server as an example. When you give an char or string. exception is raised.
Well, you can use next() to get the value as a String, then parse the value and see if a String or Integer was entered.
String str = stdin.next();
for (char c:str.toCharArray()) {
if (!Character.isDigit(c)) {
throw new IllegalArgumentException("Invalid character entered: " + c);
}
}

How do I check to see if the input is an integer?

Very Frustrated at my professor, because she did not teach try and catch concepts, neither did she teach us about throw exceptions either, so it is very difficult for me to do this program. The objective is to make a program where the user is asked to input an integer that prints "Hello World" that many times of the integer. The problem is I cannot check to make sure the user input is an integer. For instance, if the user chose to type a character or a double, how do I implement that into my code? And I cannot use throw exceptions or try and catch because we did not learn them yet.Thanks guys!!!
import java.util.Scanner;
public class PrintHelloWorld
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
int number;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
number = scan.nextInt();
System.out.print("Your integer is " + number);
int remainder = number%1;
int counts = 0;
if( number>0 && remainder == 0)
{
while(counts <= number)
{
System.out.println("Hello World!");
counts++;
}
}
else
System.out.print("Wrong, choose an integer!");
}
}
scan.hasNextInt()
will check to see if the next value in the input stream is an integer.
as such:
int number = -1;
System.out.println("Please enter an integer that shows the " +
"number of times to print \"Hello World\" : ");
//store count
if (scan.hasNextInt()) number = scan.nextInt();
if (number != -1) System.out.print("Your integer is " + number);
You can use a loop and validate the input with a regex, like this:
Scanner scan = new Scanner(System.in);
String input = null;
while (true) {
input = scan.nextLine();
if (input.matches("\\d+")) {
break;
}
System.out.println("Invalid input, please enter an integer!");
}
int number = Integer.parseInt(input);
This will keep asking for input until a valid integer is entered.
And I cannot use throw exceptions or try and catch because we did not
learn them yet.
For a first attempt, you could create a method that accepts a String as parameter. You will loop through all the chars of this String and check if each char is a digit. While this method returns false, re-ask the user for a new input.
Then use Integer.valueOf to get the int value..
public static boolean isNumber(String input)
You will have to use sc.nextLine() to get the input
The method Character.isDigit and toCharArray() will be useful

Categories

Resources