Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Variables in a loop

Tags:

java

variables

What I'm trying to do is have a loop to get a users input, convert it to an integer, create a variable and store the integer to that new variable. If the user doesn't input the word "end" it will continue to do this until the user does so. The thing I'm having trouble with is creating the variables. I'd like to just have them a, b, c, d, e, and so on. The rest of the program I can do, just need pointed in the right direction for this.

like image 745
Mike Avatar asked Jul 14 '26 09:07

Mike


2 Answers

If you don't know how many values you're going to get, you really need to store them in a Collection such as a List.

What are you going to do with the values once they are all input?

like image 62
Rachel Shallit Avatar answered Jul 15 '26 23:07

Rachel Shallit


I would use a array for this and it sounds like you need two variables:

String sInput;

int iInput[];

Then in your loop you can test to see if sInput is a number and not "end" after which you can parse it to your array:

iInput[index] = Integer.parseInt(sInput);

later you can then access each element in the array iInput[0], iInput[1]...

Be aware you must define the array size and when you do in Java you can not change it or make it bigger.

I hope this gets you going.

like image 37
Bit Avatar answered Jul 16 '26 00:07

Bit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!