构造函数中的新扫描程序对象

时间:2015-07-28 02:57:41

标签: java java.util.scanner

Java noob在这里。我的导师专门告诉我"在构造函数中实例化扫描器"。问题是,我没有在ScannerLab类中看到构造函数。我也没有看到任何遗产。我有一个名为scan的字段,它是我需要使用的java.util.Scanner类型。如何在构造函数中实例化扫描程序?

代码:

public class ScannerLab {

   private java.util.Scanner scan;

   public void echoStrings() {
      String word;      
      // create a new storage array      
      String[] myList = new String[5];
      // set for loop
      for(int i = 0; i < 5; i ++) {
         // prompt for the value
         System.out.print("Enter word " + i + ": ");
         // get the input value
         word = scan.next();
         // echo the input value
         System.out.println("You entered " + word);
         // store the input value into the array
         myList[i] = word;         
      }
      String line = "";
      // loop through the array and concatenate the values
      // put a space between the words
      System.out.println("The words you entered are: " + line);
      System.out.println("list is" + myList);
   }

   public void echoIntsAndTotal() {
      int inputValue;
      // declare an array to hold the 5 values
      for(int i = 0; i < 5; i ++) {
         // prompt for the value
         System.out.print("Enter integer value " + i + ": ");
         // get the input value
         inputValue = 23;
         // echo the input value
         System.out.println("You entered " + inputValue);
         // store the input value into the array
      }
      int total = 0;
      // loop through the array and add the values
      System.out.println("The total of your values is " + total);
   }

   public static void main(String[] args) {       
      ScannerLab lab;
      lab = new ScannerLab();      
      lab.echoStrings();
      // lab.echoIntsAndTotal();
   }

}

我试过了: 将扫描字段设置为参考变量:

private java.util.Scanner scan = new java.util.Scanner(System.in);

然后在我使用的应用方法中:

public static void main(String[] args) {       
      ScannerLab lab;
      lab = new ScannerLab(scan);

没有用。编译和运行的唯一方法是将我的字段切换到:

private static java.util.Scanner scan = new java.util.Scanner(System.in);

但是他不允许我们使用静态字段,并且仍然没有在构造函数中实例化。

构造函数在哪里,我如何在其中实例化一个新的扫描程序? 谢谢

2 个答案:

答案 0 :(得分:1)

那么编写构造函数呢?

// Constructor
public ScannerLab() {
    scan = new java.util.Scanner(System.in);
}

除此之外,这一行

System.out.println("list is" + myList);

不起作用。它将为您提供类名和哈希码,因为这是默认实现。

尝试这样的事情:

System.out.println("\nThe words you entered are:");
System.out.println(Arrays.toString(myList));

将为您提供如下输出:

The words you entered are:
[apple, banana, carrot, dududu, elephant]

答案 1 :(得分:1)

如果你的类中没有构造函数,你有一个隐含的默认构造函数(参见this question)。 You can choose to override it at any point

public class ScannerLab {
  public ScannerLab() {
    scan = new java.util.Scanner(System.in);
  }

  ...
}

来自https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

  

编译器自动为没有构造函数的任何类提供无参数的默认构造函数。此默认构造函数将调用超类的无参数构造函数。