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

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

Related

Java: show different results depending on User Console Input without try...catch statement

I try to write a programm in Java that gets user input using Scanner Class. The user has to enter any positive integer number. Depending on user actions, the results should be as follows:
The user has entered not an integer number -> the programm prints the message
Oops! You entered something different, but not an integer number, try again
The user has entered not a positive integer number -> the programm prints the message
You entered not a positive integer number, try again
The user has entered a positive integer number -> the programm prints the number
User's positive integer number - ...
I have written some code using loop and Scanner class
public static void main(String[] args) {
int userIntNum;
boolean isUserInputCorrect;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
userIntNum = 0;
System.out.println("Please, enter a positive integer number");
isUserInputCorrect = (sc.hasNextInt() && (userIntNum > 0));
// double console input for correct integer number
while (isUserInputCorrect == false) {
if (!sc.hasNextInt()) {
System.out.println("Oops! You entered something different, but not an integer number, try again");
sc.nextLine();
} else if (sc.nextInt() <= 0) {
System.out.println("You entered not a positive integer number, try again");
sc.nextLine();
} else {
break;
}
}
userIntNum = sc.nextInt();
System.out.println("User's positive integer number - " + userIntNum);
When I put in the console a positive integer number (the correct input), the programm, for some reason, asks me to enter this number twice.
Moreover, if I put first an integer number and then any non-positive number separated by space, it will print this incorrect number. And if I put first an integer number and then not an integer number separated by space, it will throw an exception.
Why does it happen and how can I fix these errors?
First, I would eliminate isUserInputCorrect. You are trying to do too much with it, instead I would loop while userIntNum is less than or equal to zero. Also, try and limit variable scope. Something like,
Scanner sc = new Scanner(System.in);
int userIntNum = -1;
System.out.println("Please, enter a positive integer number");
// double console input for correct integer number
while (userIntNum <= 0) {
if (sc.hasNextInt()) {
userIntNum = sc.nextInt();
} else {
System.out.println("Oops! You entered something different, "
+ "but not an integer number, try again");
sc.nextLine();
}
if (userIntNum <= 0) {
System.out.println("You entered not a positive integer number, try again");
}
}
System.out.println("User's positive integer number - " + userIntNum);
Expanding on Elliott's answer above, I wanted to provide an alternative solution that addresses your following point:
Moreover, if I put first an integer number and then any non-positive
number separated by space, it will print this incorrect number. And if
I put first an integer number and then not an integer number separated
by space, it will throw an exception.
The Scanner class will read tokens individually in a temporal fashion. If you look at the nextInt() function you will see it that throws InputMismatchException which you can explicitly catch.
Additionally, take a look at the Java modulus operator. Since you are explicitly looking for even values, the modulus operator is extremely valuable here.
public static void main(String[] args) {
int userIntNum = 0;
boolean isUserInputCorrect = false;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please, enter a positive integer number");
try {
userIntNum = sc.nextInt();
isUserInputCorrect = (userIntNum > 0 && userIntNum % 2 == 0);
} catch (InputMismatchException ex) {
System.out.println("Invalid input: please enter an integer value");
sc.next();
}
} while(!isUserInputCorrect);
System.out.println("User's positive integer number - " + userIntNum);
}

types cannot be converted when validating the users input for an integer

I am trying to validate a user's input and check if the inputted number is an integer. Id like to throw them an error message if the number isn't an integer. I am getting stuck on the line Integer.parseInt(number); Any suggestions would be very appreciated.
import java.util.Scanner;
public class Sums {
public static int number;
public static void main(String[] args) {
int evenSum, oddSum = 0;
int posInt;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
int number = input.nextInt();
try {
Integer.parseInt(number);
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println(number + " is not an integer.");
}
}
}
I have changed the int number = input.nextInt(); to String number = input.next(); and it works.
The issue here is that when you call Integer.parseInt(number) you are trying to parse the variable number which is an int and not a String. This means that you are doing the error checking on a conversion from an int to an Integer and not a String to an Integer.
To fix this, input a string instead of a number, then perform the conversion on the string, not the number.
...
public static void main(String[] args) {
int myNumber;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
String numberString = input.nextLine();
try {
myNumber = Integer.parseInt(number);
System.out.println("Value entered is " + myNumber);
// do what you want with the number
} catch (NumberFormatException e) {
System.out.println(numberString + " is not an integer.");
}
}
...
You don't need explicitly to convert your number to an integer, Scanner.nextInt() already does that for you, i.e. Scanner.nextInt() scans the next token of the input as an int. So just remove the line "int number = input.nextInt();" from your code. In general, Integer.parseInt() is preferable when you want to convert a String representation of an Integer value as a signed decimal integer. For instance, if you would have used Scanner.nextLine() instead of Scanner.nextInt(), then it makes more sense to convert it to a signed decimal integer if you want to perform subsequent operations using that integer value.
int number = input.nextInt();
The variable number is already an int, that is why you can not hand it over to the method. The method requires a String.
If you want to use the method like you did, you should use
input.next()
as argument because it returns the input as String and initialize number within the try block, e.g.
public static void main(String[] args) {
int evenSum, oddSum = 0;
int posInt;
System.out.println("Enter a postitive integer: ");
Scanner input = new Scanner(System.in);
try {
number = Integer.parseInt(input.next());
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
Bug here is int number = input.nextInt();
When you want to convert a String to a primitive datatype we use class.parseXXX(String)
You see I have written String in the function .parseXXX(String) Cause it takes String as a parameter and nothing else
So lets read your code
Integer.parseInt(number);
Here its .parseXXX(int) and clearly its not matching .parseXXX(String)
So in order to give String as parameter, you have accept String as input from user.
Replace this int number = input.nextInt(); with String number = input.next();
So now below code is valid cause its in .parseXXX(String)
Integer.parseInt(number);
Changed code:
int evenSum, oddSum = 0;
int posInt;
Scanner input = new Scanner(System.in);
System.out.println("Enter a postitive integer: ");
String number = input.next(); // <-- Changed
try {
Integer.parseInt(number);
System.out.println("Value entered is " + number);
} catch (NumberFormatException e) {
System.out.println(number + " is not an integer.");
}

Ensuring user input is a single integer while using Scanner [duplicate]

This question already has answers here:
How do I ensure that Scanner hasNextInt() asks for new input?
(2 answers)
Closed 6 years ago.
Desired outcome:
Accepts user input
Makes sure user inputs only 1 integer value at a time
Stores that integer in a variable
I tried to achieve this by doing the following:
Store user input in variable
Count number of tokens in variable
If there's not one token, reject the input
If the input is not of data type int, reject the input
Code:
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer:");
String myString = scan.nextLine();
int tokens = new StringTokenizer(myString, " ").countTokens();
while (tokens != 1 && !scan.hasNextInt()) {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
}
int number = scanner.nextInt();
System.out.println(number);
This code is full of holes. The output is inconsistent and undesired. It typically ends by throwing a java.util.InputMismatchException error, indicating the value it's trying to store isn't an int. I've experienced this error occur after one loop and after multiple loops, even with the same type and quantity of input (e.g. 2 strings).
Should I keep going with this code, or should I try to approach this problem from a different angle?
I've modified your program a little bit. My approach was to accept a single line of input. If the input contains more than one token, ask the user to re-enter input. If there is only one input, check if the input is an integer, if not, as the user to again provide input.
Seems to work for me:
Scanner scanner = new Scanner(System.in);
String myString;
int tokens;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
tokens = new StringTokenizer(myString, " ").countTokens();
try {
number = Integer.parseInt(myString);
} catch(NumberFormatException e) {
tokens = 0;
number = -1;
}
}while (tokens != 1);
scanner.close();
System.out.println(number);
Update: Alternate approach without using StringTokenizer
Scanner scanner = new Scanner(System.in);
String myString;
boolean validInput;
int number;
do {
System.out.println("Enter a single integer");
myString = scanner.nextLine();
try {
number = Integer.parseInt(myString);
validInput = true;
} catch(NumberFormatException e) {
validInput = false;
number = -1;
}
}while (validInput == false);
scanner.close();
System.out.println(number);
Update 2: Another approach using regular expressions to validate input before accepting it.
The Scanner allows us to use a regular expression to match the input. If the input matches the pattern, you can use it to accept the input. Otherwise, discard it and ask user to provide input again.
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a single integer");
String integerPattern = "[+-]?\\d+$"; // positive or negative and digits only
while(scanner.hasNext(integerPattern) == false) {
String x = scanner.nextLine();// capture and discard input.
System.out.println("Enter a single integer. '" + x + "' is an invalid input.");
}
int number = scanner.nextInt(); // capture input only if it matches pattern.
scanner.close();
System.out.println("number: " + number);
Hope this helps!

How would i do input validation?

Tells the user if the number entered is even or even. I need help with the input validation. The validation i need do is that the user cannot entered anything but a number. Trying to do the validation without the try and catch method.
import java.util.Scanner;
public class oddoreven {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
//declaractions
int num;
//while loop
do{
System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99.");
num = input.nextInt();
// input valid
}while(num != -99); // loop ends
// begins the method
public static void is_odd_or_even_number(int number){
int rem = number%2;
\
You can call Scanner.hasNextInt() to determine if the next input is an int (and consume anything else). Also, you might make an infinite loop and break when the input is -99 (or 99, your code tests for 99 but your prompt says -99). Finally, you should call your method. Something like,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
do {
System.out.println("Please enter a number to see whether it is "
+ "even or odd. To end type in -99.");
if (input.hasNextInt()) {
num = input.nextInt();
if (num != -99) { // <-- directions say -99.
is_odd_or_even_number(num);
} else {
break;
}
} else {
System.out.printf("%s is not a valid int.%n", input.nextLine());
}
} while (true);
}
You can use Scanner.nextLine() to get a string input. Then loop through the characters to make sure they are all digits. (assuming non-negative integers only)
string rawInput = input.nextLine();
boolean validInput = true;
for (char c : rawInput) {
if (!Character.isDigit(c)) {
validInput = false;
break;
}
}
if (validInput) {
int num == Integer.parseInt(rawInput);
// proceed as normal
}
else {
// invalid input, print out error message
}
You can use regex to check whether all the characters of string entered by user are digits or not,
num.matches("[0-9]+") // return true if all characters are digits
or
num.matches("^[0-9]*$") // return true if all characters are digits
but before that change your num = input.nextint() to num = nextLine() and make num as String. if you dont do this there is no need of validating user input as you are requiring.

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.

Categories

Resources