简体   繁体   English

我可以在同一类中使用两种不同的方法读取同一文件吗?

[英]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.

相关问题 我可以在同一类的两个方法中使用@GET批注吗? - Can I use @GET annotations in two methods in same class? 如果我在同一个类上同步了两个方法,它们可以同时运行吗? - If I synchronized two methods on the same class, can they run simultaneously? 我可以使用两个不同的线程在同一个套接字上读写吗? - Can I read and write on the same socket using two different threads? 如何同时运行两个不同的主类? - How can I run two different main class at the same time? 如何在Java中读取相同的文件两次? - How can i read the same file two times in Java? 两个线程可以在同一时间运行两种不同的方法吗? - Can two threads run two different methods at the same point of time? 两个不同的程序可以对同一个文件执行I / O同步吗? - Can two different program perform synchronization on the same file for I/O? 我可以从同一个jar文件中执行两个不同的类吗? - Can I execute Two different Classes from same jar file? 如何从两个不同的文件中读取文件,并将每个文件中的10个随机名称放到同一输出文件中,总共20个 - How can I read from two different files and put 10 random names from each for a total of 20 into the same output file Rest资源文件中的两种方法,它们的@Path相同,但mediaType输出不同 - Two methods in Rest resource file with same @Path but different mediaType output
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM