I'm very new to Java 4 1/2 weeks into my intro to java, I have to write a program that asks user for an integer, the program will then add up all integers from 1 to N and display output message the sum of integers from 1 through (integer input from user) is (this would be the sum)

here is what I have, and I'm not sure what I am doing wrong.

import javax.swing.JOptionPane;

// declare class
public class CalculateIntSum

   // main method
   public static void main( String[] args )

    // declare and initialize variables
    String numberStr, openingMessage, output;
        double number, total = 0;     
        int i = 0, N = 0, count = 1;       

    //opening message
    openingMessage = "This program will add positive integers from 1 to N.\n"
                       + " N being the integer the user inputs.";

 JOptionPane.showMessageDialog( null, openingMessage);                

 while ( i <= N )
 numberStr = JOptionPane.showInputDialog( "Enter a number: " ); //user enters a value 
         number = Double.parseDouble( numberStr );
         total += number + count; // accumulate number to total
         i++;                     // increment counter variable by 1    


     //output message to user
     output = "The sum of the integers from 1 to" + numberStr  "is" + total;  

      JOptionPane.showMessageDialog( null, output);

      System.exit(0); // terminate the GUI thread

   } // end main

} // end class

Edited by Nick Evan: Fixed formatting

6 Years
Discussion Span
Last Post by dannii

for starters, you set your N to be 0 and you never change this value, so your code will never go through your loop.


Thanks stultuske, I saw that once you pointed it out, and was able to fix my code so it would do what I wanted it to.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.