I am trying to create a simple number guessing game - java

I ask the user to input a number until the user finds it.
I'm having trouble validating every input whether the user is typing in a number or anything else like char or string.
So basically I'm trying to prevent any mismatch exception error.

If you're writing code to take input as an integer, then it should come as an error or not move on if it doesn't have an int as an input.
If you're writing code to take a char or a string as an integer, then you should use Integer.parseInt() to convert your input to an int value.

Try to parse the text as a number, and if it fails, catch the failure and prompt the user to reenter the number.
Should be enough of a hint to get you going.

You can try to parse the String as a double and catch a NumberFormatException which will indicate that the input is not a valid number.
private static boolean isNumber(String s){
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}
If you want to not allow the String "NaN" to be accepted as a number, you can check if the String is equal to "NaN" before parsing it.
private static boolean isNumber(String s){
if(s.trim().equals("NaN")){
return false;
}
try{
Double.parseDouble(s);
return true;
} catch (NumberFormatException e){
return false;
}
}

Related

Trying to validate a passed value to a method

I have a program that is trying to validate a passed value. I want a user to input anything and the method that I pass it to will validate whether the input would work.
This is my code:
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
ChequingAccount a = new ChequingAccount();
double deposit = inputCheck("Enter deposit amount: ", input);
a.setDeposit(deposit);
}
public static double inputCheck(String prompt, Scanner input) {
boolean userValid = false;
do {
System.out.print(prompt);
double user;
try {
user = input.nextDouble();
if (user < 0) {
throw new IllegalArgumentException("Value cannot be lower than 0");
}
userValid = true;
} catch (InputMismatchException e) {
System.out.println("The value entered is not a number");
user = inputCheck(prompt, input);
input.nextLine();
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
user = inputCheck(prompt, input);
}
return user;
} while (!userValid);
}
The code works except for the fact that when the method catches the InputMismatchException, the code then will loop a bunch of times and breaks the program. I thought adding a doWhile loop would solve the issue but it didn't do anything.
you don't need a loop , you need recursion
public static double inputCheck(String prompt, Scanner input) {
double user;
try {
user = input.nextDouble();
if (user < 0) {
throw new IllegalArgumentException("Value cannot be lower than 0");
}
return user;
} catch (InputMismatchException e) {
System.out.println("The value entered is not a number");
return inputCheck(prompt, input);
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
return inputCheck(prompt, input);
}
}
You're calling your own method from inside; the inputCheck method's code calls inputCheck. This is a somewhat creative way to write a loop.
You also have... a loop.
So you 2 loops, to do the job that one loop should do. That's why all heck breaks loose here. Pick one: Either use the do/while construct (so do not call yourself), or, don't loop, and call yourself. Either one can be made to work here.
The nextLine stuff is irrelevant and not the problem here (in general don't call that; just set the delimiter properly; call scanner.useDelimiter("\\r?\\n") and to get entire lines, use next(), not nextLine().
There are number of approaches that can work for this – iteration, recursion, exception catching, etc. Your solution is mixing several of them together which makes it harder to understand and also harder to fix.
Here is an example that uses a simple while loop, no recursion, no exception catching. It uses hasNextDouble() and, depending on the result, either proceeds to capture the double (by calling nextDouble()), or prints a message (along with consuming and ignoring whatever non-double token is present by calling next()).
public static double inputCheck(String prompt, Scanner input) {
while (true) {
System.out.print(prompt);
if (input.hasNextDouble()) {
double number = input.nextDouble();
if (number < 0) {
System.out.println("Value cannot be lower than 0. Please try again.");
} else {
return number;
}
} else {
System.out.println("The value entered is not a number. Please try again.");
input.next(); // consume and ignore whatever non-double input is waiting on the scanner
}
}
}

Checking for valid int

I am receiving data from Bluetooth as a byte array, I can turn this into a char array and the data will display correctly if I display it in a TextView however when I try to run my function that will iterate through all the spaces in my byte array it gets tripped up when it comes to the /u0000 (aka NULL?) character the NumberFormatException catches but it crashes after the catch code has run. A typical byte[] for me would look something like {'1','2','\u0000','\u0000'} and that would represent the number 12 being sent through Bluetooth.
My idea was to have the code check for the int value then catch the exception if it wasn't parseable or continue to run if it was. This would then set the boolean and the calling function would receive whether the character is a valid int or not.
Here is my code:
private boolean checkForInt(char c) {
boolean isInt;
try {
Integer.parseInt(c + "");
isInt = true;
} catch (NumberFormatException e){
isInt = false;
}
return isInt;
}
You could use Character.isDigit(char) on your char c.
If you are running into problems with the NUL-terminator character, when iterating over the byte array check if the ith character is NUL, if so don't try to parse it...

Verify if a String is an integer (numberFormatException)

I was trying to write a piece of code to test if a string contains an integer. I am aware of the try catch solution, but i have read it becomes bad if you call the method from other classes. What I have read is that the method will show the error, but the main of the class calling it will keep running anyway.
Therefore, I was trying to do it manually. My problem is that i am able to assess that the string is not empty and that all the characters in the string are digits, but I can't find a way to verify whether the number is too big to be sorted in an integer. Point is, i have found on stackoverflow many similar topics, but noone solve this problem without try catch.
Here is my method.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
Thanks in advance for your help!
I think the best way to do this is as pointed by Leo in the comments.
public static boolean isInteger(final String strInput) {
boolean ret = true;
try {
Integer.parseInt(strInput);
} catch (final NumberFormatException e) {
ret = false;
}
return ret;
}
Also I suggest you separate the GUI part from the checking method, let the caller decide what to do if false (for example, maybe in some situations you want to check if it's an integer but don't show the dialog).
You could modify your method to make sure the number fits within an int.
It can be done by parsing the input as long, and checking against the range of int numbers.
// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
int number_of_digits = 0;
if (str_input.isEmpty()) {
JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
for (char c : str_input.toCharArray()){
if(Character.isDigit(c)){
number_of_digits++;
}
}
if (number_of_digits == str_input.length()){
if (str_input.length > 15) // arbitrary length that is too long for int, but not too long for long
return false;
long number = Long.parseLong(str_input);
if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE)
return false;
else
return true;
}
else {
JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
}
BTW, if you allow negative inputs, you should change your check to allow '-' as the first character.
That said, I agree with all the comments that say you'd be better off to just call Integer.parseInt() and catch the exception.
How about using Regex
-?\\d+(\\.\\d+)? which accept negative and decimal numbers
Source: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}

how to check if user input is a double?

In my JSP page, I let users input their dollar balance.
Then I catch this in servlet as: String input = req.getParameter("balance");
How do I check if input variable is double? I know how to use ParseDouble, but I don't want to catch the exception. Instead, I want to pass my own error message to JSP so that users can see it when they have typing error.
Can someone help me?
You may also create a function like this:
boolean isDouble(String input) {
try {
Double.parseDouble(input);
return true;
} catch (NumberFormatException e) {
//You can send the message which you want to show to your users here.
return false;
}
}

Java - looping in try-catch block

I am working on writing a file reader, and the idea is to have the user enter a number that represents the line number from the text file. The variable that holds this number is of type int. However, when the user enters a String instead, Java throws the InputMismatchException exception, and what I want is to have a loop in the catch clause, where I will be looping until the user enters a valid value, i.e. an int. The skeleton looks like this:
public void _____ throws IOException {
try {
// Prompting user for line number
// Getting number from keyboard
// Do something with number
} catch (InputMismatchException e) {
// I want to loop until the user enters a valid input
// When the above step is achieved, I am invoking another method here
}
}
My question is, what are some possible techniques that could do the validation?
Thank you.
while(true){
try {
// Prompting user for line number
// Getting number from keyboard
// Do something with number
//break;
} catch (InputMismatchException e) {
// I want to loop until the user enters a valid input
// When the above step is achieved, I am invoking another method here
}
}
Avoid using exceptions for flow control. Catch the exception, but only print a message. Also, do need for loops within loops.
It's as simple as this:
public void _____ throws IOException {
int number = -1;
while (number == -1) {
try {
// Prompt user for line number
// Getting number from keyboard, which could throw an exception
number = <get from input>;
} catch (InputMismatchException e) {
System.out.println("That is not a number!");
}
}
// Do something with number
}
You can avoid the Exception
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
String input = sc.nextLine();
if (isNumeric(input) {
// do something
// with the number
break; // break the loop
}
}
The method isNumeric:
public static boolean isNumeric(String str) {
return str.matches("^[0-9]+$");
}
If you want use a dialog for input number:
String input = JOptionPane.showInputDialog("Input a number:"); // show input dialog

Categories

Resources