开发者

Initialize Variables in a loop

What I'm trying to do is have a loop to get a users input, convert it to an integer, create a variable a开发者_开发技巧nd 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.


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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜