English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

If the user is allowed to enter the amount of objects to be created, how do I write the code?

For example:
String[] array = new String[10]; // say the 10 is user input

Is there a way to change that 10 into a variable where the user enters a value in the console? I'm new in java so please write as simple as possible.

Thanks for any advise...

2006-08-23 17:14:00 · 2 answers · asked by carmageddon87 1 in Education & Reference Homework Help

2 answers

you can use variables as arrays dimensions.
for example

int m=(an int value from user input);
int n=(another int value from user input);
AnObject[][] myObjects=new AnObject[n][m];

if objects are primitive this code is enough. But if AnObject class is not a primitive class you have contruct all of them like this

for (int i=0;i for (int j=0;j AnObject[n][m]=new AnObject(contructor parameters);
}
}

2006-08-23 20:30:44 · answer #1 · answered by Anonymous · 0 0

Absolutely.

I can't remember the syntax for entering from the console, but after you get it into a variable you can do...

String[] array = new String[variableName];

Remember that you will probably need to convert the value entered from the console from a String into an integer. user int.intParse(variable) if I remember correctly.

2006-08-23 17:19:06 · answer #2 · answered by Michael M 6 · 0 0

fedest.com, questions and answers