Checking for valid int - java

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...

Related

I am trying to create a simple number guessing game

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;
}
}

Do While Loop Error, Stuck in while loop

I have a boolean Guess function:
public boolean guess() {
String checkInput = scanner.nextLine();
try {
guess = Integer.parseInt(checkInput);
} catch (NumberFormatException e) {
return false;
}
return true;
}
which is called by another function in a do while loop:
while (!player.guess()) {
player.guess();
}
If I enter an int, the program runs properly and terminates. But if input is a non-int character, the program gets stuck in the while loop. I don't know what's going on here.
Your guess function is designed that way.
It returns false if the input is not numeric (catch). So it stays in the loop until you input a numeric value.
Another problem is that you are calling the function twice every loop (once on the loop condition check and another inside the loop). So if you type a non numeric character on the first (loop condition) and a numeric on the second (inside the loop) it will still ask for an input a third time.
I don't know what your intention is but you probably would want something like:
while (!player.guess()) {
continue;
}
Unless you really want it to be called twice.
Your scanner.nextLine() reads the line forever, it doesn't ask for another input.
while (!player.guess()) { // Entered Integer. (!true) and loop breaks
player.guess();
}
while (!player.guess()) { // Entered Non-Integer. (!false) and program enters the loop
player.guess(); // You are not storing the result in some boolean variable
//Therefore, it doesn't matter whether true or false
//while (!player.guess()) will be checked once again
}
SOLUTION:
boolean flag = player.guess(); // capture the result
while (!flag) { // verify the result
flag = player.guess(); // capture the result again
}

Comparing String to int JAVA

I am trying to figure out how to make sure a String variable does not have a number as a string. I cannot Import anything.
I have tried
NameArray[i].equalsIgnoreCase("")) || Integer.parseInt(NameArray[i]) >= 48 && Integer.parseInt(NameArray[i]) < 58
but it did not work.
In Java 8+, you might use an IntStream to generate a range ([48, 58]) and then check if that as a String is equal to your NameArray. Something like,
if (IntStream.rangeClosed(48, 58).anyMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
You mention that you want to make sure it doesn't contain a value - so perhaps you really want noneMatch like
if (IntStream.rangeClosed(48, 58).noneMatch(x -> String.valueOf(x)
.equals(NameArray[i]))) {
}
You can try converting string to number using Integer.parseInt(string).
If it gives an Exception than it is not a number.
public boolean validNumber(String number)
{
try
{
Integer.parseInt(number);
}
catch (NumberFormatException e)
{
return false;
}
return true;
}
So, you need to check for a string which doesn't contain any numbers.
Try using regex .*[0-9].* which will check for occurrence of any numerical character in your string.
String regex = ".*[0-9].*";
// Returns true
System.out.println("1".matches(regex));
System.out.println("100".matches(regex));
System.out.println("Stack 12 Overflow".matches(regex));
System.out.println("aa123bb".matches(regex));
// Returns false
System.out.println("Regex".matches(regex));
System.out.println("Java".matches(regex));

while loop parsing Double.IsNaN improperly

Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}

How to check if there are double letters in a 4 digit code in Java

The above question might seems vague but it's actually a very simple idea which i can't seem to figure out.
It basically is a 4 digit letter code containing letters from A to F for example: ABDF, BAAF, DBAF etc.
Now I'm trying to do some post input-handling where it must become impossible to enter a letter that is already in the code cause it has to be a unique 4 digit code with no repeating letter. I've been trying to make it work but none of my code seems to work so i'm back to scratch asking you guys for help :)
I hope this is somewhat clear otherwise i'll be happy to clear it up.
Thanks in advance.
Kind of a pseudocode but it would work.
String uniquePass="";
while(uniquePass.length<4){
String userInput=getUserInputChar()
if(uniquePass.contains(userInput))
rejectInputAndNotifyUser
else
uniquePass=uniquePass+userInput
}
public static boolean hasDuplicateChars(String string) {
Set<Character> chars = new HashSet<Character>();
for (char c : string.toCharArray()) {
if (!chars.add(c)) return false;
}
return true;
}
Set is a collection that contains no duplicate elements. We will use add method which returns true if this set did not already contain the specified element.
hasDuplicateChars functions iterates over characters in the input string using toCharArray function and for loop; each character is added to the chars set which is initially empty. If add method returns false it means that we have already encountered same character before. So we return false from our function.
Otherwise input is valid and method returns true.
using this function you'll be able to see if the string contains unique characters
public static boolean checkForUnique(String str){
boolean containsUnique = false;
for(char c : str.toCharArray()){
if(str.indexOf(c) == str.lastIndexOf(c)){
containsUnique = true;
} else {
containsUnique = false;
}
}
return containsUnique;
}
Update:
This will be ran everytime a user enters a character and if it fails, this would mean there is a duplicate. You have the choice of discarding that input or showing an error.
If you're validating the complete input, you can lean on the set semantics, and a few tricks
String s = "ABAF";
int count = new HashSet<>(Arrays.asList(s.split(""))).size();
if (count - 1 == 4) {
System.out.println("All ok");
} else {
System.out.println("Repeated letters");
}
the split("") will split the string to a an array like {"","A", "B", "A", "F"}.
The new HashSet<>(Arrays.asList(s.split(""))) will create a Set with String elements, and as the Set will bounce back the elements already contained, the size of the set for e.g. "AAAF" will be 3 (it'll contain the "", "A" and "F"). This way you can use the size of the set to figure out if all letters of a String are unique
If its while typing you'll than the solution depends on the input method, but you can have something like (pseudo stuff)
if (pass.contains(letter)) {
breakAndNotifyUser();
} else {
pass+=letter;
}

Categories

Resources