2

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);
    }
}
Rakesh
  • 2,946
  • 2
  • 14
  • 28
  • Unrelated: use meaning full names please. First of all, java class names go UpperCamelCase ... and then s2 is a poor name. Why not "ExampleUser" or something alike? – GhostCat Jul 01 '19 at 15:36

1 Answers1

1

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();
  }
user7294900
  • 47,183
  • 17
  • 74
  • 157