I have some EditText in my Activity. The user has to fill them out and confirm his input. Some of the EditText are only for numbers. To make sure that there are only valid values i'm trying to cast the input to an Integer using Integer.parseInt( . . . ). The problem is no matter what the string is the NumberFormatException wont be thrown. I debuged the problem and the corosponding line is executed every time but without throwing an exception.
Here is the Code of my method:
private boolean formNotEmpty()
{
boolean returnValue = true;
for(int i = 0; i < _editText.size();i++){
if(_editText.get(i).getText().toString().trim().length() == 0)
{
returnValue = false;
_toastMessage = "Es müssen alle Felder ausgefüllt werden.";
break;
}else if(_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userPLZ))
||_editText.get(i).getHint().equals(getResources().getString(R.string.rentactivity_hint_userTelefon)))
{
try{
Integer.parseInt(_editText.get(i).getText().toString().trim());
}catch(NumberFormatException e)
{
_toastMessage += "In "+_editText.get(i).getHint().toString() +" dürfen nur Zahlen stehen. \n";
}
}
}
return returnValue;
}
I've forgotten to set returnValue in the catch block to false. The _toastMessage gets a new string if the method returns true. This is the reason i assumed that the exception is never thrown. I'm realy sorry for the trouble i caused.
Thank you very much
If you are counting on the code to throw you an exception, and you want to use this as a means to validate the data to accept only numbers, then this is not the right approach to this. Exception handling should'nt explicitly be used as an if-else like you suggest. A simpler, and perhaps more correct way to accomplish what you want would be :
Declare in the layout xml
android:inputType="number"
for that particular edittext you want to confine entries only to numbers.
When you do this, you only get option to type in numbers, when you try to fill that editText, as a user. After adding this in the xml, you would not need to depend on the Integer.parseInt() API to throw exception, for your validation.
Also you can use the attr of EditText:
android:digits="0123456789."
http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits
After that user can write only numbers.
Related
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;
}
I am working on a program that allows me to move a pen, making a mark on a canvas. At the moment, I have a method called convertToInteger in class "MyInput" (which in the class with my methods I've referred to as "reader"), which converts a string into an integer.
public int convertToInteger(String word)
{
return Integer.parseInt(word);
}
I've then tied this into my method, converting a string input into an integer.
case "move":
int distance = reader.convertToInteger(command.get(1));
brush.move(distance);
break;
Thus, in my program I can type "move 100" and the brush move 100 pixels. The code, in its current state, crashes with an exception error if I tried typing a non-integer; e.g. "move here".
In "MyInput" class, I created a boolean method that checks to see if it's a integer or not using 'try' and 'catch':
public boolean isAnInteger(String word)
{
boolean ok;
try {
Integer.parseInt(word);
ok = true;
}
catch(NumberFormatException ex) {
// Non-integer string.
ok = false;
}
return ok;
}
Then tried implementing it in my code:
case "move":
int distance = reader.convertToInteger(command.get(1));
if (reader.isAnInteger(command.get(1)) == true){
brush.move(distance);
}
else {
printError();
}
break;
When I run the code and type something like "move here" in the terminal, it throws an exception so clearly its bypassing my code - but typing "move 100" or any other valid integer works.
Any suggestions? Thanks in advance.
Your instructions are in the wrong order. Your are attempting to parse, then checking if it can be parsed. You should really check first, then try to parse.
I have a problem that when I use Integer.parseInt in this context it doesn't convert my and somehow it even kick me out of loop so it dont't want to display for example System.out.print(1) after loop like everything was crashed but i have no error. Please help. That's a part of code which cause it. variable "input" is an Arrayl
for (int i=0;i<input.size();i++)
{
if(point>Integer.parseInt(input.get(i).split(":")[1]))
{
input.set(i,highScore + System.getProperty("line.separator"));
break;
}
}
Have you verified that input.get(i).split(":")[1] gives you exactly a string that only contains digits?
Integer.parseInt(String s) throws NumberFormatException, so you should execute that code inside a try/catch block like this:
for (int i=0;i<input.size();i++) {
try {
int parsedValue = Integer.parseInt(input.get(i).split(":")[1]);
// do whatever you want to do with parsedValue
}
catch(NumberFormatException e) {
System.out.print("I caught an error!, what i was trying to parse wasn't a number");
// or any other action you consideer that needs to be done when parseInt fails
}
}
There is only one explanation (if you are sure that no exception is thrown): the input is empty. :)
I'm looking for an exception on how to catch an invalid String that is user input. I have the following code for a exception on an integer input:
try {
price = Integer.parseInt(priceField.getText());
}
catch (NumberFormatException exception) {
System.out.println("price error");
priceField.setText("");
break;
But I'm not aware of a specific exception for strings, the input is a simple JTextBox so the only incorrect input I can think of is if the user enters nothing into the box, which is what I'm looking to catch.
if (textField.getText().isEmpty())
is all you need.
Or maybe
if (textField.getText().trim().isEmpty())
if you also want to test for blank inputs, containing only white spaces/tabs.
You generally don't use exceptions to test values. Testing if a string represents an integer is an exception to the rule, because there is no available isInt() method in String.
You can do like
if (priceField.getText().isEmpty())
throw new Exception("priceField is not entered.");
You could check if priceField contains a string by using this:
JTextField priceField;
int price;
try {
// Check whether priceField.getText()'s length equals 0
if(priceField.getText().getLength()==0) {
throw new Exception();
}
// If not, check if it is a number and if so set price
price = Integer.parseInt(priceField.getText());
} catch(Exception e) {
// Either priceField's value's length equals 0 or
// priceField's value is not a number
// Output error, reset priceField and break the code
System.err.println("Price error, is the field a number and not empty?");
priceField.setText("");
break;
}
When the if-statement is true (If the length of priceField.getText() is 0) an exception gets thrown, which will trigger the catch-block, give an error, reset priceField and break the code.
If the if-statement is false though (If the length of priceField.getText() is greater or lower than 0) it will check if priceField.getText() is a number and if so it sets price to that value. If it not a number, a NumberFormatException gets thrown, which will trigger the catch-block etc.
Let me know if it works.
Happy coding :) -Charlie
if you want your exception to be thrown during the normal operation of the Java Virtual Machine, then you can use this
if (priceField.getText().isEmpty())
throw new RunTimeException("priceField is not entered.");
I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.