Search code examples
javavariableswhile-loopjoptionpane

Displaying numbers in a while loop


I'm trying to create a program where the user enters a starting number and an ending number. The program prints all the values in between including the start and end, and displays all of them on a message dialog screen. But I can't get them to display all the numbers on a single message dialog, it creates a new one for each number.

public static void main(String[] args) {

    int start;
    int end;
    int result;
    start = Integer.parseInt(JOptionPane.showInputDialog("Please enter a starting integer "));
    end = Integer.parseInt(JOptionPane.showInputDialog("Please enter an ending integer "));
    while (start <= end) {

        result = start;
        start++;

        JOptionPane.showMessageDialog(null,result);
    }
}

Solution

  • The loop is calling showMessageDialog() during each iteration. You want the loop to append each number to a string, and then, when it's done, show the entire string in the dialog.

    public static void main(String[] args) {
    
      int start;
      int end;
      int result;
    
      start = Integer.parseInt(JOptionPane.showInputDialog(
          "Please enter a starting integer "));
      end = Integer.parseInt(JOptionPane.showInputDialog(
          "Please enter an ending integer "));
    
      String msg = "";
      while (start <= end) {
        msg = msg + " " + start;
        start++;
      }
    
      JOptionPane.showMessageDialog(null, msg);
    }
    

    In production code, you'd use a StringBuilder and append() each number to it, rather than generating a new String during each iteration of the loop, because it's more efficient. But rather than distract you with implementation details, I chose to focus on the algorithm.

    Here's the StringBuilder version:

      StringBuilder msg = new StringBuilder();
      while (start <= end) {
        msg.append(start).append(" ");
        start++;
      }
    
      JOptionPane.showMessageDialog(null, msg.toString());