Reputation: 43
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
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
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
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