Boolean_functions Boolean_functions - 1 month ago 6
Java Question

Within a loop, is there a way to have the name of a variable change/depend on the value of the current index?

For example (we are told we want to go up to 'X'):

Scanner scan = new Scanner(System.in);

for (int i; i <= X; i++)
{
System.out.println("Enter the value for value " + i)'
int valuei = scan.nextInt();
}


So instead of constantly reasssining a value to the one variable 'valuei',
our program would create X number of integer variables as well as assigning them the corresponding user input as values.

'value1' gets the value the user had input as an answer at index 1

'value2' gets the value the user had input as an answer at index 2

...

'valuei' gets the value the user inputs as an answer at index i

If not possible, what would be the most efficient way to accomplish the above?

Thanks

edit: ok, well looks like I'm overthinking it and just using arrays will work. Thanks for the responses.

Answer

You can use an array

int []valuei = new int[X];

valuei [0] gets first input.

valuei [1] gets second input.

....

valuei [X-1] gets Xth input.

Scanner scan = new Scanner(System.in);

int []valuei = new int[X];

for (int i=0; i < X; i++)
{
 System.out.println("Enter the value for value " + i);
 valuei[i]=scan.nextInt();
 }
Comments