我是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/