Input Object into an array as a List in Java

Viewed 373

I am a beginner in Java. I want to get input from the user to a 2D array, and convert into a list of objects.

  • When I hardcoded the data, it could be done as this way

    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)
      );
    }
    

but, I want to get this object arrays from the user input. When I am going to do this way, it was giving me an error.

  • Code :

    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]);
       }    
    );
    
  • Error :

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

Can you give me a solution for adding objects as a list from the 2D array that user inputs?

3 Answers

First, create List then in for-loop add to the List

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]));
}

Instead of

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

try using lambda

List<Job> jobs = Arrays.stream(arr)
                .map(arrElement -> new Job(arrElement[0],arrElement[1],arrElement[2]))
                .collect(Collectors.toList());

You can try this way also using bufferedReader,

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(isr);
List<Job> jobs = new ArrayList<>();
String x = bufferedReader.readLine();
String[] y;
int count = Integer.parseInt(x);

for (int i = 0; i < count; i++) {
    y = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
    jobs.add(new Job(
            Integer.parseInt(y[0]),
            Integer.parseInt(y[1]),
            Integer.parseInt(y[2])));
}
Related