java - 在 Java 中将对象作为列表输入到数组中

标签 java arraylist multidimensional-array

我是Java初学者。我想将用户的输入获取到二维数组,然后转换为对象列表。

  • 当我对数据进行硬编码时,可以这样做

    class Job // Job Class
    {
       public int taskID, deadline, profit;
    
       public Job(int taskID, int deadline, int profit) {
       this.taskID = taskID;
       this.deadline = deadline;
       this.profit = profit;
       }
    }
    
    public class JobSequencing{
    
      public static void main(String[] args) {
      // List of given jobs. Each job has an identifier, a deadline and profit associated with it
    
      List<Job> jobs = Arrays.asList(
            new Job(1, 9, 15), new Job(2, 2, 2),
            new Job(3, 5, 18), new Job(4, 7, 1),
            new Job(5, 4, 25), new Job(6, 2, 20),
            new Job(7, 5, 8), new Job(8, 7, 10),
            new Job(9, 4, 12), new Job(10, 3, 5)
      );
    }
    

但是,我想从用户输入中获取这个对象数组。当我打算这样做时,它给了我一个错误。

  • 代码:

    Scanner scan = new Scanner(System.in);
    int count = scan.nextInt();
    
    int[][] arr = new int[count][3];
    
    for(int i =0; i<count;i++){
       String[] arrNums = scan.nextLine().split(" ");
    
       arr[i][0] = Integer.parseInt(arrNums[0]);
       arr[i][1] = Integer.parseInt(arrNums[1]);
       arr[i][2] = Integer.parseInt(arrNums[2]);
    }
    
    List<Job> jobs = Arrays.asList(
       for(int i=0 ; i< count ; i++){
          new Job(arr[i][0], arr[i][1], arr[i][2]);
       }    
    );
    
  • 错误:

    Syntax error, insert ")" to complete MethodInvocationJava(1610612976)
    Syntax error, insert ";" to complete LocalVariableDeclarationStatementJava(1610612976)
    

您能给我一个从用户输入的二维数组中将对象添加为列表的解决方案吗?

最佳答案

首先,创建列表,然后在 for 循环中添加到列表中

List<Job> jobs = new ArrayList<>();
for (int i = 0; i < count; i++) {
    jobs.add(new Job(arr[i][0], arr[i][1], arr[i][2]));
}

关于java - 在 Java 中将对象作为列表输入到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374992/

相关文章:

java - 谁能解释一下 ConcurrentModificationException?

java - 如何使用带有 List 参数的泛型函数

java - 使用接口(interface)作为父类(super class)时强制多态性的合适解决方案是什么

java - 如何使用 Thymeleaf 通过 "ID"选择列表项并定向到另一个详细信息页面?

java - 我正在开发 servlet,只有一种 deGet 和 DoPost 方法。我在那里写了一种新方法。 。我如何直接访问该新方法?

Java OutOfMemoryError 与 ArrayList<List<Integer>>

java - 为什么我得到的是数组的地址而不是值(二维数组)

javascript - 我应该如何在这个多维数组中将名称加粗?

Javascript:将多维数组展平为唯一路径数组

java - 从链接列表中删除