imulsion imulsion - 19 days ago 8
Java Question

Strange thing happening with Java applet try/catch statement

Something strange and mysterious is going on with my applet! It involves a person guessing a number, which is then compared with a random number. You keep guessing until you get it right. If you entered something like

ewjkgmvf


you would get a
NumberFormatException
on the entry field. To solve this problem, I surrounded the turning of the String into the int with try...catch. If the exception was caught, the Label was supposed to display "That is not a number!". Instead, it just said "Too low. Try again" , which was only supposed to happen if your guessed number was too low. What am I doing wrong?

I will post the whole program as it is only a short one.

Here is my code:

import java.awt.*;
import java.applet.*;
import java.util.Random;
public class Number_guess_applet extends Applet{
private static final long serialVersionUID = 1L;
Button btnClick;
TextField entry;
Label prompt;
String temp;
Random r = new Random();
int x = r.nextInt(100);
int number;
int keepGoing = 1;

public void init(){
prompt = new Label("Guess the number");
add(prompt);
entry = new TextField(10);
add(entry);
btnClick = new Button("Check your guess");
add(btnClick);
}
public boolean action(Event evt, Object arg){


temp = entry.getText();
try
{
number = Integer.parseInt(temp);
}
catch(java.lang.NumberFormatException e)
{
prompt.setText("That is not a number!");
}
if (x < number)
prompt.setText("Too high. Try again.");
else if (x > number)
prompt.setText("Too low. Try again.");
else if (x == number)
prompt.setText("Found it!");
else
prompt.setText("Invalid or not a number. Choose a number between 1 and 100");
return(true);


}
}

Tom Tom
Answer

Move the logic into the try / catch - you're executing it afterwards so it's overwriting the prompt text:

 try {
        number = Integer.parseInt(temp);
        if (x < number)
            prompt.setText("Too high. Try again.");
        else if (x > number)
            prompt.setText("Too low. Try again.");
        else if (x == number)
            prompt.setText("Found it!");
        else
            prompt.setText("Invalid or not a number. Choose a number between 1 and 100");
 } catch(java.lang.NumberFormatException e) {
        prompt.setText("That is not a number!");
 }
 return(true);
Comments