如何使用while循环处理用户输入的数组

时间:2018-09-30 08:15:36

标签: java arrays while-loop user-input

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

4 个答案:

答案 0 :(得分:0)

使用while循环并从用户那里获取输入非常简单。请参考下面的代码,您将了解如何从用户那里获取输入以及while循环如何工作。将所有代码放入您的main()函数中,并导入import java.util.Scanner;并执行并进行修改以理解代码。

   Scanner sc= new Scanner (System.in); // this will help to initialize the key board input

            System.out.println("Enter the array element");
            int N;
            N= sc.nextInt(); // take the keyboard input from user 
            System.out.println("Enter the "+ N + " array element ");
            int i =0;
            double salaries[]=new double[N]; // take the array lenght as the user wanted to enter
            while (i<N) { // this will  get exit as soon as i is greater than number of elements from user
                salaries[i]=sc.nextDouble();
                i++; // increment value of i so that it will store in next  array element
            }

答案 1 :(得分:0)

在Java上,如果您指定数组大小,则无法更改它,因此您需要在添加任何值之前先了解数组大小,但是可以使用ArrayList之类的List实现中的某个来实现添加值而不必关心数组的大小。

示例:

   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 
        }

请阅读这些文章以获取更多详细信息:
difference-between-array-vs-arraylist
distinction-between-the-capacity-of-an-array-list-and-the-size-of-an-array

答案 2 :(得分:0)

您可以使用Scanner类从用户那里获取输入

Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=sc.nextInt();
double salaries[]=new double[n];
for(int i=0;i<n;i++)
{
   salaries[i]=sc.nextDouble();
}

答案 3 :(得分:0)

您还可以使用for循环并使用Scanner类来获取键盘输入。

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        System.out.println("Please enter the length of array you want");
        Scanner scanner = new Scanner(System.in);
        int length = scanner.nextInt();
        double salaries[]=new double[length];
        System.out.println("Please enter "+ length+" values");
        for(int i=0;i<length; i++){
            scanner = new Scanner(System.in);
            salaries[i] = scanner.nextDouble();
        }
        scanner.close();
    }
}