user1781671
user1781671

Reputation: 43

Java using Scanner as a parameter for a constructor

This is a question for a school assignment, which is why I am doing it in such a way.

Anyways, I make a scanner using Stdin in the main method (Scanner stdin = new Scanner(System.in); is the line), reading data from a txt specified when the program is run. This Scanner works as expected in the main, however I need to use it in an custom class that has Scanner as an argument:

    public PhDCandidate(Scanner stdin)
    { 

    name = stdin.nextLine();
    System.out.println(name); //THIS NEVER RUNS
    preliminaryExams = new Exam[getNumberOfExams()];

    for(int i = 0; i <= getNumberOfExams(); i++)
    {
        preliminaryExams[i] = new Exam(stdin.nextLine(), stdin.nextDouble());
    }
    System.out.print("alfkj");
   }

At this point any call of the Scanner will just end the program, with no exceptions or errors thrown. Only calling .next() works. I could make the program work, but it would be hacky, and I really don't understand what is happening. I suspect I am missing a very simple concept, but I'm lost. Any help would be appreciated.

Upvotes: 4

Views: 13120

Answers (3)

Yogendra Singh
Yogendra Singh

Reputation: 34367

Please make sure you are not closing and re-initializing Scanner stdin before calling constructor as I suspect that is the problem i.e. if you are doing something like below:

        Scanner stdin = new Scanner(System.in);
        .........
        stdin.close(); //This will close your input stream(System.in) as well  

        .....
        .....

        stdin = new Scanner(System.in);
        PhDCandidate phDCandidate = new PhDCandidate(stdin);

stdin inside the constructor will not read anything as input stream System.in is already closed.

Upvotes: 3

icanc
icanc

Reputation: 3577

Add a set Name method in your PhDCandidate class. This way you can create a PhDCandidate object inside your main method and print the name or do whatever from main.

public static void main(String[] args) {

    PhDCandidate c = new PhDCandidate();
    c.setName(stdin.nextLine());
}

Upvotes: 1

PermGenError
PermGenError

Reputation: 46428

your code works fine for me. after creating the scanner in the main pass it as an argument.

 public Test(Scanner stdin)
        { 
System.out.println("enter something");
        name = stdin.nextLine();
        System.out.println(name); //THIS NEVER RUNS


        System.out.print("alfkj");
       }
    public  static void main(String...args)throws SQLException {
        new Test(new Scanner(System.in));
}

output: enter something
        xyzabc
        alfkj

Upvotes: 1

Related Questions