2012-10-31 70 views
4

这是一个学校任务的问题,这就是为什么我这样做的原因。使用Scanner作为构造函数的参数的Java

总之,我在主要方法(Scanner stdin = new Scanner(System.in);是行)中使用Stdin制作扫描仪,从程序运行时指定的txt中读取数据。这种扫描仪按预期工作为主,不过,我需要用它在具有扫描仪作为参数的自定义类:

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"); 
    } 

此时扫描仪的任何调用将刚刚结束程序,没有例外或抛出的错误。只有调用.next()的作品。我可以让程序工作,但这会很冒险,我真的不明白发生了什么。我怀疑我错过了一个非常简单的概念,但我迷路了。任何帮助,将不胜感激。

+1

”此时,Scanner的任何调用都将结束程序,不会抛出异常或错误。“究竟在什么时候?程序在哪里结束? –

+1

我不认为你的程序实际终止。我认为你的控制台正在等待输入。尝试在控制台上输入一些名称。 – Jimmy

+0

@ Code-Guru:只要我尝试使用扫描器(除了stdin.next(),所有其他方法都会中断),就会结束,所以立即尝试使用.nextLine() – user1781671

回答

1

你的代码适合我。在主通道中创建扫描仪之后,将其作为参数。

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 
+0

问题是,尽管System.in(),它实际上是从.txt文件读取。如果我要用Scanner stdin = new Scanner(新文件(“file.txt”)替换扫描仪结构;扫描仪仍然以相同的方式运行。 – user1781671

1

在您的PhDCandidate类中添加一个Name方法。通过这种方式,您可以在main方法内创建一个PhDCandidate对象,并打印名称或执行main操作。

public static void main(String[] args) { 

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

请确保您不关闭并调用构造函数之前重新初始化Scanner stdin我怀疑是IE,如果你正在做的事情像下面的问题:

 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在构造函数中会由于输入流System.in已关闭,因此未读取任何内容。 “

相关问题