java - 从用户输入获取数组值

标签 java arrays

我正在尝试使用扫描仪从用户处获取整数和 double 值。我在设置数组本身的值时遇到问题。这是我的代码:

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 是另一个类的访问器。 另外,我不能使用数组列表。

最佳答案

你的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();
}

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

关于java - 从用户输入获取数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29711250/

相关文章:

java - GZIP解压代码抛出异常

java - 如何使用 LWUIT 居中对齐列表

java - 使用公钥验证签名

javascript - 根据条件修改 Redux 中的对象数组

python - 给定字节缓冲区、数据类型、形状和步幅,如何创建 Numpy ndarray

arrays - 如何从二维数组中选择一维数组?

c# - 将通用列表<string> 转换为 byte[ ]

java - 如何记录带有变体的代码? (用于 ifs 的 JavaDoc)

java - Jboss Java EE 容器和一个 ExecutorService

html - 如何将多个 CSS 类添加到单个数组