Java 数组实例化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1987182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array Instantiation
提问by user228390
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 to an array that is able to hold fiveTicketMachine
objects
- 使
readings
变量引用一个能够容纳六十个double
值的数组 - 使
urls
变量指向一个能够容纳九十个String
对象的数组 - 使
machines
变量引用一个能够容纳五个TicketMachine
对象的数组
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];
采纳答案by John Feminella
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:
那么您重新声明了 的类型i
,这是一个错误。相反,只需执行以下操作:
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 = ...;
回答by mportiz08
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];