将文本文件读入数组

时间:2017-02-25 19:40:25

标签: arrays java-io

我试图将女孩和男孩的名字存储在阵列中。

除了将文件存储到数组中之外,我获得了大部分代码。

这是 girls.txt 的样子

Emma 125125

Elaina 415545

Kim 545454

Boys.txt:

Devan 45645

Tom 4545

Chris 4879797

我需要帮助将文件中的名称和数字存储到数组boynames数组和girlnames数组中。我在代码中显示我需要帮助的地方

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Project1Names {
   public static void main(String[] args) {
    Scanner inputStream = null;
    String[][] boynames = new String[1000][2];
    String[][] girlnames = new String[1000][2];
    String line = null;
    boolean isFoundB = false;
    boolean isFoundG = false;
    try {
        inputStream = new Scanner(new FileInputStream("boys.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("Problem opening file boys.txt");
        System.exit(0);
    }

    Scanner inputStreamGirls = null;
    try {
        inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("Problem opening file girls.txt");
        System.exit(0);
    }
       int count = 0;
        while (count < 1000){
            inputStream =  boynames[count][0]; //Error here
            inputStream =  boynames[count][1]; //here
            count++;
        }

        count = 0;

        while (count < 1000 ){
            inputStreamGirls = girlnames[count][0]; //here
            inputStreamGirls = girlnames[count][1]; //here
            count++;
        }
      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
      String answer = keyboard.next(); 

        count = 0;
        while(count < 1000){
            if (boynames[count][0] == answer){
                System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " +  boynames[count][1] +  " namings");
                isFoundB = true;
            }
            if (girlnames[count][0] == answer){
                System.out.println(girlnames[count][0] +  " is ranked " + count +  " among girls with " + girlnames[count][1] + " namings");
                isFoundG = true;
            }
            count++;
        }

        if(isFoundB == false){
            System.out.println(answer + " is not ranked among the top 1000 boy names.");
        } 
        if(isFoundG == false){
            System.out.println(answer + " is not ranked among the top 1000 girl names.");
        }

    inputStreamGirls.close();
    inputStream.close();
    keyboard.close();
}
}

1 个答案:

答案 0 :(得分:1)

您需要调用扫描仪方法来实际读取输入文件。

scanner.next()从输入中读取一个字符串标记。

所以不是这一部分:

inputStream =  boynames[count][0]; //Error here
inputStream =  boynames[count][1]; //here

你会这样做:

boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();