SumOfIntegers /* * Filename: "SumOfIntegers.java" * Created by 1,000_naymes for ICt 352 * Purpose: to add integers entered by a user */ import javax.swing.JOptionPane; public class SumOfIntegers { public static void main( String[] args ) { /************************************************************** declare and initialize variables **************************************************************/ String openingMessage, int1InputMessage, int1String, errorMessage, outputMessage; int int1 = 0, total = 0; openingMessage = "Welcome to 1KN's SumOfIntegers program, which will ask you for a positive integer and \ncompute the sum of all integers up to and including your number."; JOptionPane.showMessageDialog( null, openingMessage ); int1InputMessage = "Please enter your positive integer: "; int1String = JOptionPane.showInputDialog( int1InputMessage ); int1 = Integer.parseInt( int1String ); // converting string to double; for ( int i = int1; i > 0; i-- ) { total += i; } if(int1 < 0) { errorMessage = "Oops! You entered invalid data, please try again!"; JOptionPane.showMessageDialog( null, errorMessage ); } else { outputMessage = "The sum of integers 1 through " +int1 + " is " + total; JOptionPane.showMessageDialog( null, outputMessage ); } System.exit(0); } //end main } //end class
Page 1