input a number on scanner - java

I am trying to create a simple Java program where the user should input his age. If the user entered for example a letter instead of a number, he will get a message.
What I would like to do is that in addition to the message the user should be asked for another input and that input will be checked again to see if it is a number.
Can anyone know how can I achieve that?
System.out.println("2 - Set The Age");
Scanner b = new Scanner(System.in);
if (b.hasNextDouble()) {
double lage = b.nextDouble();
setAge(lage);
addEmployeeMenu();
} else {
System.out.println("You should type only numbers!");
}

You can use a while loop like this
Scanner b = new Scanner(System.in);
double lage;
while (true) {
System.out.println("2 - Set The Age");
if(b.hasNextDouble()){
lage = b.nextDouble();
break;
}else b.nextLine();
}
The point is, get your number and check it inside a while loop, repeat as long as the input is not correct

You can also use NumberFormatException:
while (true) {
System.out.println("Set the age: ");
String input = sc.next();
try {
int x = Integer.parseInt(input);
System.out.println("Your input '" + x + "' is a integer");
break;
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
}
}

Related

Loops in Java after user inputs values

public static void main(String args[])throws IOException{
validNumbers = new int[200];
Scanner sc1 = new Scanner(new File("validNumbers.txt"));
int i = 0;
while(sc1.hasNextInt()) {
validNumbers[i++] = sc1.nextInt();
}
// Creating loop for what the user enters
boolean newValidator = true;
Scanner scanner = new Scanner(System.in);
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
// If found, the calculations will get displayed
if(validator(num)) {
System.out.print("The calculated value to this account is: " + calculator(num));
newValidator = false;
System.out.println("\n" + "Would you like to enter another account number? (y/n)");
String ans = "";
ans = scanner.nextLine();
// Needed the false, if not the code would keep asking to "Enter account number: "
if (ans.equals("y")) {
System.out.print("Enter the account number: ");
String num2 = scanner.nextLine();
System.out.print("The calculated value to this account is: " + calculator(num2));
} else if(ans.equals("n")) {
newValidator = false;
System.out.println("** Program Exit **");
}
}
// Wanted to add a loop for the user to decide if they want to continue iff wrong account is inputed
else {
System.out.println("Not valid account number" + "\n\n" + "Would you like to try again? (y/n)");
String ans = "";
ans = scanner.nextLine();
if(ans.equals("y")) {
newValidator = true;
}
// How the program terminates if the user does not wish to continue
else if(ans.equals("n")) {
newValidator = false;
System.out.println("Not valid input, the program is now terminated!");
}
}
}
}
}
(Using Java) The code is doing the following:
1.) When the user enters a correct number it sees the number(in the file) and adds the digits
2.) When it is not in the file, it knows the number is not there and tells the user to try again and if the user doesn't want to, it ends the program.
***** (Using Java) What the code is not doing:
1.) After they entered the right code, the program is to ask the user if they want to enter another account(with the adding of an account if so). Then this is where I have the problem, the loop is ending after this second go and I need it to keep asking if they want to enter another account number unit the user wants to exit.*****
There's no need to have a nested question asking for another account number, the while loop itself will ask the user again when it repeats.
Simply ask the user if they want to enter another and then exit the loop if the don't. The while loop drops out when "newValidator" is set to false:
boolean newValidator = true;
while(newValidator) {
System.out.print("Enter the account number: ");
String num = scanner.nextLine();
if(validator(num)) {
System.out.println("The calculated value to this account is: " + calculator(num));
}
else {
System.out.println("Not valid account number!");
}
System.out.println("\n\nWould you like to enter another account number? (y/n)");
String ans = scanner.nextLine();
if (ans.equals("n") || ans.equals("N")) {
newValidator = false;
}
}
System.out.println("** Program Exit **");

How do i check the input is an integer in java [duplicate]

This question already has answers here:
How to loop user input until an integer is inputted?
(5 answers)
Closed 3 years ago.
In my program I want an integer input by the user. I want an error message to be show when user inputs a value which is not an integer.
And How can I do this in loop. i am just a beginner please help me.
//code that i already try
Scanner input = new Scanner(System.in);
int age;
String AGE ;
System.out.print("\nEnter Age : ");
AGE = input.nextLine();
try{
age = Integer.parseInt(AGE);
}catch (NumberFormatException ex){
System.out.print("Invalid input " + AGE + " is not a number");
}
You use an while loop and break on sucess
int age;
while (true) { // wil break on sucess
Scanner input = new Scanner(System.in);
System.out.print("\nEnter Age : ");
String AGE = input.nextLine();
try{
age = Integer.parseInt(AGE);
break;
}catch (NumberFormatException ex){
System.out.print("Invalid input " + AGE + " is not a number");
}
}
This is the better way to check user input is integer or Not -
public static void onlyInteger() {
int myInt = 0;
System.out.println(" Please enter Integer");
do {
while (!input.hasNextInt()){
System.out.println(" Please enter valid Integer :");
input.next();
}
myInt = input.nextInt();
}while (myInt <= 0);
}
Hope this will help.
If you are trying to capture the age input as an integer, you would not need the integer array as such
'int age [] = new int [100];'
You can use Scanner's nextInt() method to capture integer input.
This will throw InputMismatchException exception in case the input is not an integer.Try below code.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Age: ");
try {
int number = input.nextInt();
System.out.println("Age entered " + number);
} catch (InputMismatchException e) {
System.out.println("Incorrect Input for Age.Please enter integer Integer value");
}
}
To check the input is an integer or any number :
Step 1 is to Read the input as Java Object, then
Object o = new Integer(33);// or can be new Float(33.33)...
if(o instanceof Number) {
System.out.println(o +" is number");// do your thing here
}
The abstract class Number is the superclass of platform classes representing numeric values that are convertible to the primitive types byte, double, float, int, long, and short.
JavaDoc Number

Stop reading standard input in Java

The following code will give me what I want which is the type of data entered (int, double, or string) however, when I run the code it is as if it expects another input before it will execute. I hope I'm on the right path.
or
Enter some stuff: 43
3
You have entered an integer: 43
It will not run until I enter another character in this case the 3 below 43.
Thanks for looking.
public static void main(String[] args)
{
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.print ("You have entered an integer: "+ input);
}
else if (in.hasNextDouble())
{
System.out.print ("You have entered a double: "+ input);
}
else if (in.hasNextLine())
{
System.out.print ("You have entered a string: "+ input);
}
}
I would use try and catch in order to found the right data type. Don't use multiple inputs otherwise you will get the error that you got, just use in.next() once and then handle the value as below:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
try {
int v = Integer.parseInt(input);
System.out.print ("You have entered an integer: " + input);
} catch (NumberFormatException nfe1) {
try {
double v = Double.parseDouble(input);
System.out.print ("You have entered a double: " + input);
} catch (NumberFormatException nfe2) {
System.out.print ("You have entered a string: " + input);
}
}
}
Output 1:
Enter some stuff: 7
You have entered an integer: 7
Output 2:
Enter some stuff: 3.0
You have entered a double: 3.0
Output 3:
Enter some stuff: sfsdfasd
You have entered a string: sfsdfasd
I think you are doing it incorrectly. If you want to know the type of the data you entered, why would you read it first? You are first reading and storing it in input variable and determining the type of the next entered input. So, the message is also wrong. I've altered your code to get desired output
public static void main(String[] args) {
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
// input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.println ("You have entered an integer: "+ in.nextInt());
}
else if (in.hasNextDouble())
{
System.out.println ("You have entered a double: "+ in.nextDouble());
}
else if (in.hasNextLine())
{
System.out.println ("You have entered a string: "+ in.nextLine());
}
}

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.

Make a code repeat loop if user input a non-numeric character?

Goal:
If the user enters a non-numeric number, make the loop run again.
Also is there another (more efficient) way of writing the numeric inputs?
public static void user_input (){
int input;
input = fgetc (System.in);
while (input != '\n'){
System.out.println("Please enter a number: ");
if (input == '0' == '1' ..... '9'){
//Execute some code
}
else {
System.out.println("Error Please Try Again");
//Repeat While loop
}
}
}
EDIT
I need the while loop condition. Simply asking, how do you repeat the while loop? Also no scanner methods.
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue. Try this:
public static void user_input() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
}
Output
Enter a number.
w
Input is not a number, continue
Enter a number.
3
Correct input, exit
Try this one
System.out.println("Please enter a number: ");
Scanner userInput = new Scanner(System.in);
while(!userInput.hasNextInt()) {
System.out.println("Invalid input. Please enter again");
userInput = new Scanner(System.in);
}
System.out.println("Input is correct : " + userInput.nextInt());
How about this
public static void processInput() {
System.out.println("Enter only numeric: ");
Scanner scannerInput;
while (true) {
scannerInput = new Scanner(System.in);
if (scannerInput.hasNextInt()) {
System.out.println("Entered numeric is " + scannerInput.nextInt());
break;
} else {
System.out.println("Error Please Try Again");
}
}
}

Categories

Resources