Crash!

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The Integer.parseInt() method crashes.

Crash!

More correctly: the method throws a NumberFormatException, which the Java system catches and then prints out a stack trace:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string "rats"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at FahrenheitPanel$TempListener.actionPerformed(FahrenheitPanel.java:52)
         . . . . and so on . . . .

The proper way to deal with this problem is to use exception handling, the subject of chapters 80 and 81. Here is the actionPerformed() method modified to deal with bad user input. Look it over, but don't worry about the details until after you have read the above chapters.

  public void actionPerformed( ActionEvent evt)  
  {
    String userIn = inFahr.getText() ;
    
    try
    {
      fahrTemp = Integer.parseInt( userIn ) ;
      celsTemp = convert( fahrTemp ) ;   
      outCel.setText( celsTemp+"" );
    }
    
    catch ( Exception ex )
    {
      outCel.setText( "Re-enter F" );  
    }  
   
    repaint();   
  }

Essentially what happens is that if anything goes wrong here:

    try
    {
      fahrTemp = Integer.parseInt( userIn ) ;
      celsTemp = convert( fahrTemp ) ;   
      outCel.setText( celsTemp+"" );
    }

an exception will be "thrown" (will happen) and the following will execute:

    catch ( Exception ex )
    {
      outCel.setText( "Re-enter F" );  
    }  

which writes an error message in the ouput text field.

QUESTION 8:

Look at the stack trace (above). What string did the user enter, that could not be converted into an integer?