How to take multiple inputs via scanner from the user in the constructor?

Viewed 95

I want to initialize the constructor which is in another class with the multiple inputs taken in for loop in the main method of another class. but the output is coming only one input. kindly solve my problem.

s1.java

import java.util.*;
public class s1 {
    public static void main(String args[]) {
        String name="";int roll=0;
        Scanner sc=new Scanner(System.in);
        for(int i=0;i<2;i++) {
            name=sc.nextLine();
            roll=sc.nextInt();

            s2 sample=new s2(name,roll);

            sample.display();

        } 
    }
}

s2.java

public class s2 {
    String name="";int roll=0;
    s2(String name,int roll) {
        this.name=name;
        this.roll=roll;
    }
    void display() {
        System.out.println(name+" "+roll);
    }
}
1 Answers

If you want more then 1 time change the condition i<2 which restrict loop for one iteration.

Change to i<10 for example for getting uoto 9 times (10-1) inputs/outputs

Add condition

 if(sc.hasNextInt()) {
      roll=sc.nextInt();
      s2 sample=new s2(name,roll);
      sample.display();
  }
Related