jessruss256 SNS
jessruss256 SNS

Reputation: 23

how to list numbers between two numbers in Java

I am trying to create a java program that lists all integers between two variables. One is the lowest(inclusive) the other is the max(also inclusive). This is my program so far:

    int highNum, lowNum;

    //converts and sets user inputs of low and high values to double
    lowNum = Integer.parseInt(minInput.getText());
    highNum = Integer.parseInt(maxInput.getText());
    String output = null;


     for (int i = lowNum + 1; i < highNum; i++)
    output = Integer.toString(i);   

    //outputs sting containing the list of numbers
    outputLabel.setText(output);

Before I converted this from a System.out and it worked but when i tried to convert it to a UI with netbeans I can no longer get it to list the numbers. Before I had this working:

    int min, max;
    min = 1;
    max = 10;
    for (int i = min + 1; i < max; i++)
        System.out.println(i);

Upvotes: 1

Views: 11510

Answers (2)

J-J
J-J

Reputation: 5871

In Java 8 you can do it in this way using IntStream

    int lowNum = Integer.parseInt(minInput.getText());
    int highNum = Integer.parseInt(maxInput.getText());

    StringBuilder sb = new StringBuilder();

    IntStream.rangeClosed(lowNum, highNum).forEach(no -> {
        sb.append(no);
    });

    outputLabel.setText(sb.toString());

Upvotes: 7

Elliott Frisch
Elliott Frisch

Reputation: 201497

Concatenate each of the values to your String, as is you get only the last value.

int lowNum = Integer.parseInt(minInput.getText());
int highNum = Integer.parseInt(maxInput.getText());
StringBuilder sb = new StringBuilder(String.valueOf(lowNum));
for (int i = lowNum + 1; i <= highNum; i++) {
    sb.append(", ").append(i);
}
outputLabel.setText(sb.toString());

Upvotes: 0

Related Questions