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.");
Related
At the moment my error exception handling returns an error if the field is empty - how can I expand this to include all characters which are not positive integers?
Button hdButton=new Button();
hdButton.setText("Save");
hdButton.setOnAction(e ->
{
if(memoryField.getText().isEmpty())
{
dsdisplay2.setText("ERROR: You must enter a positive number in order to set the
memory\n");
}
else
{
s1.setHardDisk(Integer.parseInt(hardDisk.getText()));
dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());
}
Wrap Integer.parseInt() in a try block and catch the NumberFormatException.
try {
int size = Integer.parseInt(hardDisk.getText());
s1.setHardDisk(size);
dsdisplay2.setText("The Hard Disk size for your PC has been set to: " + s1.getMemory());
} catch (NumberFormatException e) {
dsdisplay2.setText("ERROR: You must enter a positive number in order to set the memory\n");
}
This way, you won't need to validate the input before setting s1.setHardDisk as the Integer.parseInt will throw an exception if the input is malformed.
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;
}
For example, here I put it only once, but I know that I can put it several times. What is the difference?
try{
if(tasks.size() <= 0){
System.out.println("Nothing to remove, no tasks");
}
else{
System.out.println("Enter index of task to remove");
int index = input.nextInt();
input.nextLine();
tasks.remove(index);
}
}
catch(InputMismatchException ex){
System.out.println("Please enter only numbers");
}
catch(IndexOutOfBoundsException ex){
System.out.println("Invalid index number");
}
}
finally will be called always, regardless if you cough exception or not so yes, there is a difference.
Anyway assuming you are using Scanner you should avoid using try-catch as part of your logic (they should be used only if exceptional situations happen since creating exception may be expensive). Instead try to prevent throwing exceptions with little help of hasNextInt method.
So you can try with something like:
System.out.println("Enter index of task to remove");
while (!input.hasNextInt()){
System.out.println("That was not proper integer, please try again");
input.next();// to let Scanner move to analysing another value from user
// we need to consume that incorrect value. We can also use
// nextLine() if you want to consume entire line of
// incorrect values like "foo bar baz"
}
//here we are sure that inserted value was correct
int int index = input.nextInt();
input.nextLine();// move cursor after line separator so we can correctly read
// next lines (more info at http://stackoverflow.com/q/13102045/1393766)
The difference is clarity and simplicity.
The finally block will always execute, if present. Code which is common to the entire block can be located there. In the future if a different response is required it can be changed in a single location.
When common code is spread out in multiple locations you run the risk of changing some but not all instances which can result in unexpected failures.
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.
I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.