【问题标题】:Java using Scanner as a parameter for a constructorJava 使用 Scanner 作为构造函数的参数
【发布时间】:2012-10-31 20:30:14
【问题描述】:

这是一个学校作业的问题,这就是我这样做的原因。

无论如何,我在 main 方法中使用 Stdin 制作了一个扫描仪(Scanner stdin = new Scanner(System.in); 是行),从程序运行时指定的 txt 读取数据。此 Scanner 主要按预期工作,但是我需要在以 Scanner 作为参数的自定义类中使用它:

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

此时,任何对 Scanner 的调用都将结束程序,不会引发异常或错误。只有调用 .next() 有效。我可以让程序工作,但它会很老套,我真的不明白发生了什么。我怀疑我错过了一个非常简单的概念,但我迷路了。任何帮助将不胜感激。

【问题讨论】:

  • "此时任何对 Scanner 的调用都会结束程序,不会抛出异常或错误。"究竟在什么时候?程序在你的代码哪里结束?
  • 我认为您的程序实际上并未终止。我认为您的控制台正在等待输入。尝试在控制台上输入一些名称。
  • @ Code-Guru:每当我尝试使用 Scanner 时它就会结束(stdin.next() 除外,所有其他方法都会中断),因此在尝试使用 .nextLine() 时立即结束
  • 你的问题解决了吗?
  • 嘿,谢谢大家的帮助。原来问题出在考试课上,以及扫描仪的工作方式。发生的事情是,当我在 main 中调用 nextInt() 时(以及所示代码中的 nextDouble() ),它读取 int (或 double )但不会前进到下一行。这导致后续的 nextLine() 调用返回一个空字符串,因为没有剩余内容,但是扫描器所在的行仍然没有超过换行符,并且 txt 中的每个标记都在不同的行上。 S0 是的,我愚蠢的问题。

标签: java constructor java.util.scanner


【解决方案1】:

请确保您在调用构造函数之前没有关闭并重新初始化Scanner stdin,因为我怀疑这是问题所在,即如果您正在执行以下操作:

        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 已经关闭。

【讨论】:

    【解决方案2】:

    您的代码对我来说很好。在 main 中创建扫描仪后,将其作为参数传递。

     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
    

    【讨论】:

    • 问题是尽管有 System.in(),它实际上是从 .txt 文件中读取的。如果我用 Scanner stdin = new Scanner(new File("file.txt"); 替换 Scanner 构造,则 Scanner 仍然以相同的方式运行。
    【解决方案3】:

    在您的 PhDCandidate 类中添加一个 set Name 方法。这样,您可以在 main 方法中创建一个 PhDCandidate 对象并打印名称或从 main 执行任何操作。

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

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多