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.
-
4Can you post your current (non-working) code and explain where exactly you are having problems?Oded– Oded2011-04-20 19:04:07 +00:00Commented Apr 20, 2011 at 19:04
-
1Note to downvoters/closers - Homework questions are valid, and the OP has indicated clearly that this in one such question.Oded– Oded2011-04-20 19:05:55 +00:00Commented Apr 20, 2011 at 19:05
-
1@Oded Well it's tagged homework, but it still reads like "write me the code" :/Ivo Wetzel– Ivo Wetzel2011-04-20 19:06:48 +00:00Commented Apr 20, 2011 at 19:06
-
2@Ivo - "point me in the right direction" sounds to me like exactly the right thing to ask with regard to homework.Rachel Shallit– Rachel Shallit2011-04-20 19:07:49 +00:00Commented Apr 20, 2011 at 19:07
3 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?
Comments
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.
Comments
If you are in a loop, odds are you don't need a new variable for every iteration in the loop, so instead of having a solution like
int input1;
int input2;
int input3;
int input4;
int input5;
for (int index = 0; index < 5; index++) {
if (index == 0) {
input1 = getInput();
}
if (index == 1) {
input2 = getInput();
}
if (index == 2) {
input3 = getInput();
}
if (index == 3) {
input4 = getInput();
}
if (index == 4) {
input5 = getInput();
}
}
you can probably live with a solution like
int input;
for (int index = 0; index < 5; index++) {
input = getInput();
... handle input before going through next loop iteration ...
}
note that solutions which use the switch statement are just optimizations of the undesirable "too many if's" solution.