I implemented a circular list in Java. The code asks for the int values to be entered, and I wish to terminate the input list with an "END". The code works but throws a runtime exception: NumberFormatException.
try{
while(true){
newnode=new Node();
oldnode.next=newnode;
newnode.prev=oldnode;
System.out.print("Enter value:");
try{
ctrlstr=bfr.readLine();
}
catch(Exception ex){
ex.printStackTrace();
}
if (ctrlstr=="END") break;
newnode.val=Integer.parseInt(ctrlstr);
oldnode=newnode;
i++;
}
}
catch(Exception ex){
ex.printStackTrace();
}
Here:
if (ctrlstr=="END")
you're comparing strings using ==, which always checks for reference identity. Instead, you should use equals:
if (ctrlstr.equals("END"))
or perhaps (if you want just a false result when ctrlstr is null)
if ("END".equals(ctrlstr))
A few extra notes:
Catching Exception is usually a bad idea - you should catch more specific exceptions
Catching an exception and then continuing anyway after printing it is usually a bad idea
Your code will be more readable if you indent appropriately
Your code will be more readable if you always use braces for if statements etc
Try
ctrlstr.equals("END") instead.
Related
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'm new to java and I'm trying to account for possible errors that might come up in my program. I'm creating a calculator and converting the inputs from infix to postfix to calculate the result. I want to try accounting for mismatched parenthesis in the input, but I'm having trouble. For example, when converting from infix to postfix, when a ) is reached, it will pop numbers from the stack and put them onto the new postfix list. In one case where there may not be a matching left parenthesis present (the while loop reaches the end of the stack without coming across a (, it should throw an exception. I've implemented the following code, but it doesn't seem to be working:
else if(tok.equals(")")){
while(stack.peek().equals("(") == false){
try{
Operator o = stack.pop();
nlist.add(o);
} catch(EmptyStackException e){
System.out.println(e.getMessage());
}
stack.pop();
}
Then in the other file which constructs the GUI and processes the inputs, I entered:
try{
java.util.List<Token> postfix = ExpressionManager.infixToPostfix(infix);
// build the expression
Expression exp = ExpressionManager.buildExpression(postfix);
// display the results
}catch(ArithmeticException e){
entryField.setText(e.getMessage())
}
Any suggestions?
stack.peek() throws EmptyStackException before you enter inside try-catch block (I assume you expect that pop will throw the exception).
Second block doesn't show how the ArithmeticException is thrown, so, not sure what you expecting here.
If you want to re-throw an exception you can do
catch(EmptyStackException e){
throw new ArithmeticException("empty stack, bad mathematical expression.", e);
}
So I'm trying to parse an numeric input in my EditText box. I'm using Integer parse to parse input into int.
#Override
public void afterTextChanged(Editable s) {
int temp;
try{
temp=Integer.parseInt(s.toString());
//do something
}catch (NumberFormatException e){
temp=someOtherNumber;
}
}
I want to continue app even if user entered invalid number.
Is that possible?
Yes this is possible. Put only catch able code in try catch block. write your remaining code after above catch block.
NumberFormatException you should put when you are confident enough that
1.) Editable s, s is not null. // if not - use Exception class here
If that ius not the case, then catching more prcise exception ie. NumberFormatException is enough. you have already put a catch block, so exception will not be propagated, and you can still continue with your app.
basic Structure
try{
// do your stuff here 1
}catch(NumberFormatException nfe){
// do your stuff here 2
}
// do your stuff here 3
Either do your stuff at 1 and 2 both or just at 3
First check for Editable s it should not null then go further., If you want to catch any exception other than NumberformatException.
then change Catch(NumberFormatException e) to this catch (Exception e). If you have any query please let know.
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 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.