只是一个基本的新手问题,我看不到在线找到好的答案。
我正在为一门类(class)编写代码,我发现自己将扫描器传递给了很多方法。
第一个问题一般来说是不受欢迎的吗?按下一个键会在运行时中断吗?
// Countinously prompt the user for a file.
Scanner input = null;
while ( input == null ){
System.out.println ( "What is the name of the file containing each student's responses to the 10 questions? " );
try {
input = new Scanner ( new File ( in.nextLine ( ) ));
} catch ( FileNotFoundException e ) {
System.out.println ( "You must input a valid file name." );
}
}
//Print and store student answers
ArrayList <String> answers = new ArrayList <String> ();
studentResponses ( input, answers );
//Analyze the answers
ansAnalysis( input );
如您所见,我将扫描仪传递给了一些方法,作为初学者,我只是不习惯它,并且认为如果这是一种常用技术,我会看到更多示例。我想我可以创建另一个对象,但这似乎更容易。
最佳答案
如果这些只是单个类中的方法,您不妨将扫描器声明为实例变量(在所有方法之外声明它)。
关于java - 将扫描仪传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602675/