为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUX布斯 2021-10-20 11:37:16
我刚开始学习 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 

        }


查看完整回答
反对 回复 2021-10-20
  • 3 回答
  • 0 关注
  • 189 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信