I am writing a simple Java application where the user provides two inputs; a starting number and an ending number. Once a button is clicked, the application should display all numbers between the starting number and the ending number on the screen.
Ex. (1 2 3 4 5) if starting = 1
and ending = 5
Here is the loop I am using to output the numbers
Int starting = 1;
Int ending = 5;
for(starting; starting <= ending; starting++){
//"Output" is a JLabel object
Output.setText(starting);
}
I would expect this to set the content of Output
to 1 2 3 4 5
. Though by the end of the loop, the content of Output
is just the last number in the sequence (5 in this case).
Could someone please explain why I am seeing this behavior?
You are overriding the text in the JLabel in every iteration. That's why the JLabel always shows the last number.
Concatenate all the integers in a single string, then after the loop completes, set the text of the JLabel to be the concatenated string.
String result = "";
for (int starting = Integer.parseInt(Start.getText()); starting <= ending; starting++){
result += starting;
}
output.setText(result);
Btw: you have syntax errors.