"new double"的目的
The purpose of "new double"
public class JAVA_Guevarra {
public static void main(String[] args) {
//These are the variables
double empBasicPay[] = {4000,5000,12000,6000,7500};
double empHousingAllow[] = new double[5];
int i;
//This program computes for the payment of the employees
for(i=0; i<5; i++){
empHousingAllow[i] = 0.2 * empBasicPay[i];
//This loop statement gets 20% of the employee basic payment
}
System.out.println("Employee Basic and House Rental Allowance");
for(i = 0; i<5; i++){
System.out.println(empBasicPay[i] + " " + empHousingAllow[i]);
//This prints out the final output of the first loop statement
}
}
}
这条语句中的new double[5]
是做什么的?
不只是 new double
,new double[5]
为最多 5 个双精度数创建数组
作为 oracle doc 解释得很好 (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
所以double empHousingAllow[] = new double[5];
为五个双精度数组分配内存
Java中的new
关键字用于创建对象。在这种情况下,正在创建的对象是一个包含五个双精度数的数组。
您可能想看看 this question,它更详细地描述了数组的声明。
其实这个概念在你定义一个数组的时候就需要尺寸,以后你就不能再改变尺寸了。
不能像
那样直接给内存块赋值
double d[5];
d[0] = 10.05;
您需要创建特定类型的内存块。
这就是为什么您需要以这种方式定义一个数组。
double d[] = new double[5]
或
double d[5];
d[0] = new double like that.
然后您可以将值添加到该块。
public class JAVA_Guevarra {
public static void main(String[] args) {
//These are the variables
double empBasicPay[] = {4000,5000,12000,6000,7500};
double empHousingAllow[] = new double[5];
int i;
//This program computes for the payment of the employees
for(i=0; i<5; i++){
empHousingAllow[i] = 0.2 * empBasicPay[i];
//This loop statement gets 20% of the employee basic payment
}
System.out.println("Employee Basic and House Rental Allowance");
for(i = 0; i<5; i++){
System.out.println(empBasicPay[i] + " " + empHousingAllow[i]);
//This prints out the final output of the first loop statement
}
}
}
这条语句中的new double[5]
是做什么的?
不只是 new double
,new double[5]
为最多 5 个双精度数创建数组
作为 oracle doc 解释得很好 (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
所以double empHousingAllow[] = new double[5];
为五个双精度数组分配内存
Java中的new
关键字用于创建对象。在这种情况下,正在创建的对象是一个包含五个双精度数的数组。
您可能想看看 this question,它更详细地描述了数组的声明。
其实这个概念在你定义一个数组的时候就需要尺寸,以后你就不能再改变尺寸了。
不能像
那样直接给内存块赋值double d[5];
d[0] = 10.05;
您需要创建特定类型的内存块。 这就是为什么您需要以这种方式定义一个数组。
double d[] = new double[5]
或
double d[5];
d[0] = new double like that.
然后您可以将值添加到该块。