Array Instantiation
Can you help me out with this question please.
Question: Given the following array declarations
double readings[];
String urls[];
TicketMachine[] machines;
write assignments that accomplish the following tasks:
- make the
readings
variable refer to an array that is able to hold sixtydouble
values - make the
urls
variable refer to an array that is able to hold ninetyString
objects - make the
machines
variable refer t开发者_开发问答o an array that is able to hold fiveTicketMachine
objects
My answer:
//declare and instantiate object
double readings [] = new double [60];
String urls [] = new String [90];
TicketMachine machines [] = new TicketMachine [5];
The error I am getting is this:
Main.java:16: readings is already defined in main(java.lang.String[])
double readings [] = new double [60];
^
Main.java:17: urls is already defined in main(java.lang.String[])
String urls [] = new String [90];
^
Main.java:18: machines is already defined in main(java.lang.String[])
TicketMachine machines [] = new TicketMachine [5];
Once you declare the variables, you don't need to mention their type again on future assignments.
Thus, if you do:
int i;
int i = 5;
then you've redeclared the type of i
, which is an error. Instead, just do:
int i;
i = 5;
Or even better, you can combine the two into one statement:
int i = 5;
Since the variables in your particular example have already been declared as a particular type, then you can just do:
readings = ...;
urls = ...;
machines = ...;
you've already declared those variables, so now you can just instantiate them
readings = new double[60];
urls = new String[90];
machines = new TicketMachine[5];
精彩评论