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());
}
}
Related
I was trying to write a program that prompts the user to read two integers and displays their sum and my program should prompt the user to read the number again if the input is incorrect. That's what I came up with:
import java.util.*;
public class NumFormatException {
public static void main(String[] args) throws NumberFormatException {
Scanner input=new Scanner(System.in);
System.out.println("Enter 2 integers: ");
int num1=0;
int num2=0;
boolean isValid = false;
while (!isValid) {
try
{
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
}
catch(NumberFormatException ex)
{
System.out.println("Invalid input");
}
}
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
}
}
My main goal is to put the user in a situation to re-enter an integer if the input is incorrect. When I enter two integers, operation work well but my problem is with the exception: when I enter for example a instead of an integer, my program crashed.
There are two problems here. First, If a nextXYZ method of Scanner encounters a wrong input, it won't throw a NumberFormatException but an InputMismatchException. Second, if such an exception is thrown, the input token won't be consumed, so you need to consume it explicitly again:
try {
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
} catch (InputMismatchException ex) { // catch the right exception
System.out.println("Invalid input");
// consume the previous, erroneous, input token(s)
input.nextLine();
}
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.
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");
}
}
I am VERY new to Java, I am trying to do a unit conversion program from Fahrenheit to Celsius and I am stun on the validation loop. This is what I got.
// Validation
do {
isNumber = true;
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
while (!input.hasNextDouble()) {
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
isNumber = false;
input.next();
}
fahrenheit = input.nextDouble();
} while (!isNumber);
as you can see what I am trying to validate is that the user doesn't enter a string. but when I run the program it gets stuck on some sort of loop and it says
What is the temperature in Fahrenheit?: something <-- what I input
Oops! Try entering only numerical characters.
and that's it. it doesn't go back to the the input or anything, it just stays there until I enter a number and then it goes back to
What is the temperature in Fahrenheit?:
To clarify, my problem is only with the validation loop, because when I enter a number it works just fine. The problem ONLY appears when I enter a string.
Example code:
import java.util.Scanner;
public class QuickTester {
public static void main(String[] args) {
double fahrenheit;
Scanner input = new Scanner(System.in);
// Validation
while(true) {
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
if (!input.hasNextDouble()) {
System.out.println("Oops! " +
"Try entering only numerical characters.\n");
// Clear away erroneous input
input.nextLine();
}
else {
fahrenheit = input.nextDouble();
break; // Get out of while loop
}
}
input.close();
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}
Input/Output:
What is the temperature in Fahrenheit?: abc
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: banana
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: 36.5
Temperature in Fahrenheit: 36.5
Note:
Revised the code. You do not need a while loop within a do-while loop.
Check if the input is a double, break out of while loop if it is indeed a double value.
Something like this will do
Scanner input = new Scanner(System.in);
double fahrenheit;
do {
System.out.print("What is the temperature in Fahrenheit?: ");
try {
fahrenheit = input.nextDouble();
//Do your work
break;
} catch (InputMismatchException ex) {
input.nextLine();
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
}
} while (true);
this will do the trick.
public class Main
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
System.out.print( "What is the temperature in Fahrenheit?: " );
// If alphabetical characters are entered
while ( !input.hasNextDouble() )
{
System.out.println( "Oops! Try entering only numerical characters." );
System.out.println();
input.next();
}
//Do Fahrenheit to Celsius calculation
}
}
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");
}
}
}