Web design tools - Chapter 2 Introduction to Java Applications 69 Common
Chapter 2 Introduction to Java Applications 69 Common Programming Error 2.9 Forgetting to call System.exitin an application that displays a graphical user interface prevents the program from terminating properly. This omission normally results in the command window preventing you from typing any other commands. Chapter 14 discusses in more detail the reason that System.exitis required in GUI-based applications. 2.5 Another Java Application: Adding Integers Our next application inputs two integers (whole numbers, like 22, 7 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. This program uses another predefined dialog box from class JOptionPanecalled an input dialog that allows the user to input a value for use in the program. The program also uses a message dialog to display the sum of the integers. Figure 2.9 shows the application and sample screen captures. 1 // Fig. 2.9: Addition.java 2 // An addition program. 3 4 // Java extension packages 5 import javax.swing.JOptionPane; // import class JOptionPane 6 7 public class Addition { 8 9 // main method begins execution of Java application 10 public static void main( String args[] ) 11 { 12 String firstNumber; // first string entered by user 13 String secondNumber; // second string entered by user 14 int number1; // first number to add 15 int number2; // second number to add 16 int sum; // sum of number1 and number2 17 18 // read in first number from user as a String 19 firstNumber = 20 JOptionPane.showInputDialog( “Enter first integer” ); 21 22 // read in second number from user as a String 23 secondNumber = 24 JOptionPane.showInputDialog( “Enter second integer” ); 25 26 // convert numbers from type String to type int 27 number1 = Integer.parseInt( firstNumber ); 28 number2 = Integer.parseInt( secondNumber ); 29 30 // add the numbers 31 sum = number1 + number2; 32 33 // display the results 34 JOptionPane.showMessageDialog( 35 null, “The sum is ” + sum, “Results”, 36 JOptionPane.PLAIN_MESSAGE ); Fig. 2.9An addition program in action (part 1 of 2). Fig. 2. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01
Note: In case you are looking for affordable webhost to host and run your web application check Vision cheap hosting services