我刚开始学习 Java,我需要关于如何修改程序的帮助,以便在使用 while 循环验证输入时将数组大小作为用户输入,以便拒绝无效整数。此外,使用 while 循环,获取键盘输入并为每个数组位置分配值。我将不胜感激任何帮助!这是代码:double salaries[]=new double[3];salaries[0] = 80000.0;salaries[1] = 100000.0;salaries[2] = 70000.0; int i = 0;while (i < 3) { System.out.println("Salary at element " + i + " is $" + salaries[i]); i = i + 1;}
3 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
在 java 上,如果您指定数组大小,则无法更改它,因此在添加任何值之前您需要知道数组大小,但是您可以使用 List 实现,例如ArrayList能够添加值而无需关心数组大小.
例子 :
List<Double> salarie = new ArrayList<Double>();
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salarie.add(sc.nextDouble());
i++; // increment value of i so that it will store in next array
}
添加回答
举报
0/150
提交
取消