如何将 while 循环与用户输入的数组一起使用

我刚开始学习 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;

}


HUX布斯
浏览 190回答 3
3回答

PIPIONE

在 java 上,如果您指定数组大小,则无法更改它,因此在添加任何值之前您需要知道数组大小,但是您可以使用 List 实现,例如ArrayList能够添加值而无需关心数组大小.例子 :&nbsp; &nbsp;List<Double> salarie = new ArrayList<Double>();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; while (i<N) { // this will&nbsp; get exit as soon as i is greater than number of elements from user&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; salarie.add(sc.nextDouble());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++; // increment value of i so that it will store in next&nbsp; array&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java