从用户输入获取数组值

时间:2015-04-17 23:53:38

标签: java arrays

我正在尝试使用扫描仪从用户那里获取整数和双精度值。我无法设置值到阵列本身。这是我的代码:

import java.util.Scanner;

public class MainClass {

    public static void main(String[] args) {
        final int SIZE = 7;
        int[] arr = new int[SIZE];
        int[] arr2 = new int[SIZE];
        double[] dub = new double[SIZE];

        Scanner sc = new Scanner(System.in);

        PayRoll p = new PayRoll();

        for(String i: p.AccEmp()){
            System.out.println("How many hours were worked by the this employee number: " + i);
             arr = sc.nextInt();
            p.SetHRS(arr);

            System.out.println("What is the pay for this employee number: " + i);
            dub = sc.nextDouble();
            p.setPR(dub);


        }

    }

}

P是一个实例,accEmp是另一个类的访问者。 另外,我不能使用Array List。

1 个答案:

答案 0 :(得分:1)

您的arr变量是一个int数组。 Scanner.nextInt将读取和int,但不是数组。

arr = sc.nextInt()行不会编译。将arr更改为int或将值添加到数组中。

我相信,既然您似乎在循环员工,那么您应该保留对循环索引的引用并添加到该索引处的数组:

for(int i = 0; i < p.accEmp().length/* or .size() if it's a list */; i++)
{
    arr[i] = sc.nextInt();
}

并将其合并到循环中,即获得双精度值的部分:
dub[i]=sc.nextDouble();