简体   繁体   English

如何从文本文件中的 Java 中的字符串数组打印一个元素(索引)?

[英]How to print one element (index) from Array of Strings in Java from a text file?

so recently i started to picked java to learn, and i want to make a Word Per Minutes software but because i only know how to use text file as database in Java, it started to made me confuse.所以最近我开始选择 java 来学习,我想做一个 Word Per Minutes 软件,但因为我只知道如何在 Java 中使用文本文件作为数据库,它开始让我感到困惑。

so i have text.txt file, i read the.txt file into a string using scanner but i split it into words as arrays so it can appear in the label (JavaFX), lets say i want 10 words at a time, if they complete typing all 10 words, than next 10 index of words should appear as well, probably using some random() method.所以我有 text.txt 文件,我使用扫描仪将 .txt 文件读入字符串,但我将其拆分为 arrays 的单词,因此它可以出现在 label(JavaFX)中,假设我一次想要 10 个单词,如果他们完成所有 10 个单词的输入,接下来的 10 个单词索引也应该出现,可能使用了一些 random() 方法。

but so far i did not find how to print spesific array index (each word) from a text file especially if the data it self not orginaly as arrays.但到目前为止,我还没有找到如何从文本文件中打印特定的数组索引(每个单词),特别是如果数据本身不是 arrays。 i tried few method but it didnt work i know it is easier if i just type bunch of words into array in the main class, then call it later but, i wonder if i can print spesific index of word.我尝试了几种方法,但没有奏效thank you谢谢你

here is my code so far到目前为止,这是我的代码

        File txt = new File("/text.txt");
        Scanner scan = new Scanner(txt);
        
        String line;
        String[] word;
        
        while (scan.hasNextLine()) {
        line= scan.nextLine();
        word= line.split(" ");
    
            for(int i=0; i<word.length; i++) {
                
                System.out.println(word[i]);
            }

[My Ouput] https://i.stack.imgur.com/loIeX.png [我的输出] https://i.stack.imgur.com/loIeX.png

[Text File that im using] http://textfiles.com/100/captmidn.txt [我使用的文本文件] http://textfiles.com/100/captmidn.txt

I think you can do this, to find an index of a String in array.我认为您可以这样做,以在数组中查找字符串的索引。

    public static int findIndex(String[] someArray, String indexString){
    for(int i = 0; i < someArray.length; i++){
        if(someArray[i].equalsIgnoreCase(indexString))
            return i;
    }
    return -1;
}

If this method finds a String inside an array, it returns its index.如果此方法在数组中找到字符串,则返回其索引。 If not, returns -1.如果不是,则返回 -1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM