Prev: Dialog Box Input-Output | Next:
This program reads numbers, adding them as they are read, and displays
the sum. It uses in embedded assignment (that "=" in the if statement
is assignment, not comparision, then tests the result. If the user clicks
on CANCEL, JOptionPane.showInputDialog returns null instead
of a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// File : dialog/AddingMachine.java
// Purpose: Adds a series of numbers.
// Reads until user clicks CANCEL button.
// Author : Fred Swartz
// Date : 2005 Apr 26
import javax.swing.*;
public class AddingMachine {
public static void main(String[] args) {
//... Local variables
String intStr; // String version of the input number.
int total = 0; // Total of all numbers added together.
//... Loop reading numbers until the user clicks CANCEL.
while ((intStr = JOptionPane.showInputDialog(null, "Enter an int or CANCEL.")) != null) {
int n = Integer.parseInt(intStr.trim());
total = total + n; // Add this number into the total
}
//... Output the total.
JOptionPane.showMessageDialog(null, "The total is " + total);
}
}
|