Java using Scanner as parameter for constructor

This is a question for the school assignment, so I do it this way.

In any case, I make a scanner using Stdin in the main method (Scanner stdin = new Scanner (System.in); this is a line), reading data from the txt specified when the program starts. This scanner works as expected basically, however I need to use it in a custom class that has the 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 to the scanner will simply end the program, without any exceptions or errors. Only the .next () call works. I could make the program work, but it would be hacked, and I really don’t understand what is happening. I suspect that I am missing a very simple concept, but I am lost. Any help would be appreciated.

+4
source share
3 answers

Please make sure that you do not close and initialize the Scanner stdin before calling the constructor, as I suspect this is a problem if you do 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 will not read anything inside the constructor, since the System.in input stream is already closed.

+3
source

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 
+1
source

Add a name method to your PhDCandidate class. Thus, you can create a PhDCandidate object inside the main method and print the name or do something from the main.

 public static void main(String[] args) { PhDCandidate c = new PhDCandidate(); c.setName(stdin.nextLine()); } 
+1
source

Source: https://habr.com/ru/post/1443315/


All Articles