Im trying to check whether the input from the User is an int or not.
Heres my code so far:
static int readInt(Scanner userInput) {
int intValue = 0;
try {
System.out.print("Please enter a number:");
intValue = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
Input.readInt(userInput);
}
return intValue;
}
The problem is: if I first give it input which is not a number and then after that i give it a number it always returns 0. If i give it a number the first attempt it returns the number I have given it.
What am I missing?
Thanks in advance
edit: Im only allowed to use Integer.parseInt and Exceptions.
To avoid your problem, in the catch block you need to assign this Input.readInt(userInput) to your variable. like this :
intValue = Input.readInt(userInput);
It looks like you are not setting the variable in the catch
intValue = Input.readInt(userInput);
Recursion is overhead here. use loop:
Integer result = null;
do {
System.out.print("Please enter a number:");
try {
result = Integer.parseInt(userInput.nextLine());
} catch (NumberFormatException ex) {
System.out.print("Not a number");
}
} while(result==null);
return result;
Related
I am just trying to get code to work where the code asks again for an answer, if text or a symbol is entered, instead of a required integer:
import java.util.Scanner;
class timecalc {
int hrs = 0;
int min = 0;
static int hourflag = 0;
static int minflag = 0;
Scanner sc = new Scanner(System.in);
public int getHours() {
try {
hourflag = hourflag + 1;
if (hourflag > 1) {
System.out.println("Invalid month Please enter hours again:");
}
System.out.println("Enter month:");
return hrs = sc.nextInt();
} catch (InputMisMAtchException e) {
System.out.println("entered invalid input " + e);
}
}
Have reviewed answers already given but cant get a workable solution
Any ideas?
I won't give you the entire code, but just a hint or psuedo-code. As an exercise you can implement it as per your requirement.
System.out.println("Enter month:");
while (true) {
try {
int min = sc.nextInt();
break;
} catch (InputMismatchException ex) {
System.err.println("Invalid input, please enter again");
sc.nextLine(); // <----- advance the scanner
}
}
Here the logic is to loop until we get the right input. If it is an invalid input, the loop never breaks.
Also as a side-note, I would recommend you to create just one method to fetch correct inputs and call it respectively from other methods. Rather than duplicating this logic everywhere.
I have a try-catch that is meant to catch anything that is not an integer. When I enter a non integer (e.g. 5.6) it tells me only integers are allowed and lets me try again (as it should). But if I enter a non-integer again it doesn't say anything and will keep taking inputs, leaving output blank.
if (choicesObjects == b) {
System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
input.next();
}
//method stuff
}
The try/catch statement is not a loop. It will always be executed once.
Of course, if there is a loop inside the try block, that block will keep executing until terminated. But such a loop requires an explicit command like while or for to be used.
Apparently what happens when entering a non-integer value (e.g., 5.6), is that the nextInt() statement throws an Exception and goes to the catch block. A better explanation can be given if the full code of the method is provided.
For this you could define a function, something like this should work
private int getNextInt(Scanner input) {
boolean isInt = false;
int userInput;
while(!isInt) {
try {
userInput = Integer.valueOf(input.next());
isInt = true;
} catch(NumberFormatException e) {
// Do nothing with the exception
}
}
return userInput;
}
This should run until an input given was an int and then return said int
You can update your code to something like this -
Scanner in = new Scanner(System.in);
int num = 0;
while(true) {
try{
num = in.nextInt();
break;
}catch(Exception e){
//print statements
System.out.println("Try again");
}
}
System.out.println("Done");
something like this
Boolean check = true;
while (check) {
if choicesObjects == b {
enter code here` System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
check = false;
System.out.println("Object: Right triangle");System.out.println("\nEnter length of Right triangle:");
input.next();
}
//method stuff
}
}
`
So I was just trying to create a simple program with bit more complicated code.
What I was asked to do was write a program which controls whether it's a positive or negative number (I know, it's easy).
What I was trying to do was to catch what was being entered, so if its not a float it will say to use a comma instead of point or enter a number instead of String.
package example1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class numbritest
{
public static void main(String[] args)
{
float num;
Scanner sisse1 = new Scanner(System.in);
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
}
if (num < 0) //kui arv väiksem
{
System.out.println("Number " +num +" on negatiivne.");
System.out.println("Seega on arv väiksem nullist");
}
else //Kui arv on suurem või võrdne
{
System.out.println("Number " +num +" on positiivne.");
System.out.println("Positiivsed arvud on suuremad");
System.out.println("või võrdsed nulliga.");
}
System.out.println();
System.out.println("Programm lõpetada!");
}
}
Sorry that it's in Estonian, but I hope you get my point.
Change float num; to float num = 0.0f; and it should work properly
What you should do is create a loop and ask user to input number as long as the number is not correct:
So this code:
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
}
Should be in a loop - for example:
boolean incorrectNumberFormat;
do
{
incorrectNumberFormat = false;
try
{
System.out.println("Sisesta number:");
System.out.println("Kaks komakohta on lubatud");
num = sisse1.nextFloat();
}
catch(InputMismatchException exception) //juhul kui sisestab miskit muud
{
System.out.println("Kontrolli kas kasutasid koma!");
sisse1.nextLine();
incorrectNumberFormat = true; //repeat the loop;
}
} while(incorrectNumberFormat);
By the way - comma won't generate the exception (for me 3,3 doesn't), but 3%3 should give you the exception.
The loop can be created in various ways it's just an quick example.
I'd change it to
Float num = null;
(note we're now using a Float object rather than float primitive, so it can be null) and then use a while condition:
while (num == null) {
try {
//...
num = sisse1.nextFloat();
} catch (InputMismatchException e) {
//give error
}
}
This will not put anything into num until the num = ... line succeeds, so it'll stay null whenever it fails. This is better than just setting it to 0.0f, because otherwise it'll cause problems if the user enters zero.
Initialize the local varible before use;
In these case compiler consider that try block may execute or not so that num.nextFloat() may execute or not so compiler throws error: variable num might not have been initialized.
so that change float num; to float num=0.0f;
I have been trying to stop the exceptions but I cannot figure out how.
I tried parseInt, java.util.NormalExceptionMismatch etc.
Does anyone have any insight how to fix this problem? Formatting is a bit off due to copy and paste.
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
if (!intFind.hasNextInt())
intFind.next();
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
}
}while(select < 0)
Other methods I have tried :
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
{
try{
select = intFind.nextInt();
}catch (java.util.InputMismatchException e)
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
return;
}
}
}while(select < 0)
It seems to me that you want to skip everything until you get an integer. This code here skips any input except an integer.
As long as there is no integer available (while (!in.hasNextInt())) discard the available input (in.next). When integer is available - read it (int num = in.nextInt();)
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt()) {
in.next();
}
int num = in.nextInt();
System.out.println("Thank you for choosing " + num + " today.");
}
}
Quick sample of how to catch exceptions:
int exceptionSample()
{
int num = 0;
boolean done = false;
while(!done)
{
// prompt for input
// inputStr = read input
try {
num = Integer.parseInt(inputStr);
done = true;
}
catch(NumberFormatException ex) {
// Error msg
}
}
return num;
}
IMO, the best practice is to use nextLine() to get a String input, then parseInt it to get the integer. If unparsable, just complain back to the user and request re-entry.
Remember you may have to do a second nextLine() (discard the input) to clear up the buffer.
I am accepting an input from user as an integer using Scanner.nextInt(). How do I verify that he enters an integer, and not an alphabetic character?
The nextInt() method will throw an InputMismatchException if the input is not an int. So you could catch that exception and perform a conditional operation. Alternatively, checkout the hasNextInt() which will return a boolean indicating whether the next value is an int.
if (scanner.hasNextInt()) {
int i = scanner.nextInt();
} else {
System.out.println("Not an int");
}
It will throw an exception if int is not entered as input. Just catch that exception and now you know the user has entered an unparsable value.
Scanner.nextInt()
If a user enters an alphabet and you expect an int, you can test for the int with Scanner.hasNextInt() and if it is false message the user.
Scanner input = new Scanner(System.in);
int i;
System.out.print("Insert an integer number: ");
while(true)
{
try
{
i = input.nextInt();
break;
}
catch(InputMismatchException e)
{
System.out.print("You have to insert an integer number, try again: ");
}
}
Wrap it in a try / catch. See this post.
try {
num = reader.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
}
Also, if you notice, in the post this is wrapped up in a loop until a valid integer is input.
I guess you could use a try catch block if there is an Exception if it's not an int.
try {
int aInt = new Scanner(System.in).nextInt();
} catch (InputMismatchException e) {
//handler-code
}