[英]Can I read the same file in two different methods within the same class?
I'm very new to coding. 我对编码非常陌生。 I'm learning java in a class from no experience at all. 我完全没有经验,正在上课学习Java。 I am using a text file with words on a new line for input. 我正在使用一个文本文件,在新行上输入单词。 The class I am creating has an object that uses string from the given file, Words, and a method with type String, getWord, which is supposed to output a random word from the given file. 我正在创建的类有一个对象,该对象使用给定文件Words中的字符串,还有一个类型为String getWord的方法,该方法应该从给定文件中输出一个随机单词。 Here is an unfinished example of the code. 这是未完成的代码示例。
public class Words {
public Words(String filename) throws FileNotFoundException {
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
}
public String getWord(Random rand){
}
}
When I try to do something within getWord, like in.hasNextLine, I receive a message that "in cannot be resolved". 当我尝试在getWord中执行某些操作(如in.hasNextLine)时,收到一条消息,提示“无法解决”。 Am I able to use that same scanner from Words in getWord? 我可以在getWord中使用Word中的同一扫描仪吗? I tried making a new File object in getWords but I am unable to input the variable filename. 我试图在getWords中创建一个新的File对象,但无法输入变量filename。
Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks :) 谢谢 :)
May be you should change your program like this. 也许您应该像这样更改程序。
public class Words {
Scanner in;
public Words(String filename) throws FileNotFoundException {
File inFile = new File(filename);
in = new Scanner(inFile);
}
............
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.