简体   繁体   中英

Java: searching a string array from a CSV file

I am new at Java so please bear with me.

I need help for one of my assignments again. Now it involves FileI/O.

The task that I have to do is:

I have to read a .csv file. The values that's inside the file are:

Christopher Lee,54.0
Stanley Wright,90.5
Oliver Stewart,75.8
Jessica Chang,34.65

As the task said, I must store the contents on the file into two arrays. One for the names, and one for the test marks. I should read the file at least twice, once to check how many names are in the file and a couple more times to actually read the file (to get the names and marks). So basically, I should have an array to store the names as Strings, and an array to store the marks of the student as real numbers.

I should line up the arrays (egstudents[0] should store the name of the first student and marks[0] should store the mark of the first student

After I stored the contents of the .csv file into an array I have to display a following menu to the user. If the user pressed 1, it should prompt the user to enter the name of a student. If the user pressed 2, the program should exit. If the name exists, it should display the test mark for the student entered. If the student does not exist then I must output a message indicating so to the user, yet the program should not end but return to the above menu.

This is my code so far:

public static void main(String[] args) 
{
    Scanner sc = new Scanner(System.in);
    String fileName = "file:///Documents/Java/marks_file.csv"; // Opens the file
    String[] arrayString = new String[6]; // String length inside the file
    int numLines, selection = 0;
    double[] arrayReal = new double[6]; // Number length inside the file
    numLines = getNumLines(fileName); // Gets the length of the file
    readFile(arrayString, arrayReal, fileName);

    // Selection menu
    do 
    {
        System.out.println("Select an option:");
        System.out.println("1. Display mark");
        System.out.println("2. Exit");
        selection = sc.nextInt();

        if (selection == 1) 
        {
            System.out.println("Enter your full name");
            {
                // Do something
            }

        } 
        else if (selection == 2) 
        {
            System.out.println("Goodbye");
        }

    } 
    while (selection == 1);
    //System.out.println("Number of arrays: " + numLines);
}

// Method to get the length of the .csv file
public static int getNumLines(String fileName) 
{
    FileInputStream fileStrm = null;
    InputStreamReader rdr;
    BufferedReader bufRdr;
    String line;
    int lineNum = 0;
    try 
    {
        fileStrm = new FileInputStream(fileName);
        rdr = new InputStreamReader(fileStrm);
        bufRdr = new BufferedReader(rdr);
        line = bufRdr.readLine();

        while (line != null) 
        {
            lineNum = lineNum + 1;
            line = bufRdr.readLine();
        }
        fileStrm.close();
    } 
    catch (IOException e) 
    {
        try 
        {
            if (fileStrm != null) 
            {
                fileStrm.close();
            }
        } 
        catch (IOException ex2) 
        {
            // Nothing to do
        }
        System.out.println("Error in file processing: " + e.getMessage());
    }

    return lineNum;
}
// Method to store the values to arrays
public static void readFile(String[] arrayString, double[] arrayReal, String fileName) 
{
    Scanner sc = new Scanner(System.in);
    FileInputStream fileStrm = null;
    InputStreamReader rdr;
    BufferedReader bufRdr;
    String line;

    try 
    {
        fileStrm = new FileInputStream(fileName);
        rdr = new InputStreamReader(fileStrm);
        bufRdr = new BufferedReader(rdr);

        for (int i = 0; i < arrayString.length; i++) 
        {
            line = bufRdr.readLine();
            arrayString[i] = processString(line);
            arrayReal[i] = processReal(line);
        }

    } 
    catch (IOException e) 
    {
        try 
        {
            if (fileStrm != null) 
            {
                fileStrm.close();
            }
        } 
        catch (IOException ex2) 
        {
            // Nothing to do
        }
        System.out.println("Error in file processing: " + e.getMessage());
    }
}
// Stores the String lines to array
public static String processString(String line) 
{
    String string;
    String[] lineArray = line.split(",");
    return string = lineArray[0];
}

// Stores real number lines to array
public static double processReal(String line) 
{
    double real;
    String[] lineArray = line.split(",");
    return real = Double.parseDouble(lineArray[1]);
}

So far, I finished the "reading the file" part and processing the contents from a .csv file to an array.

I am not too sure how to prompt a user to search a string array from a .csv file. I tried looking at other sources, even at this website but I have no luck at all. I tried the Scanner.next() method but that doesn't work at all. Maybe I just missed something. Also, I am not sure if I did the "reading the file twice" right.

Am I on the right track? I am need of some guidance here

与其存储到数组中,不如告诉您将数据传递到通用arraylist中,然后使用get()方法查询结果。

You are making simple thing difficult.

Just use a HashMap with name as the keys and test-score as the values.

  1. You open file
  2. You read each line and translate each line to an entry of hash map
  3. When a text is input to the console, you just get it from hash map, if existed return the value, if not then back to number 3

First of all I want to say that I'd use a Map instead of two arrays but I'll show you a solution using two arrays.

You were close to the solution. One of you problems is that scanner.next() only reads the input until the first whitespace. That's why you need to use scanner.nextLine() . This method reads the complete line. And the code could look something like that:


Solution with two arrays

Scanner sc = new Scanner(System.in);
System.out.print("Please enter name of student: ");
String name = sc.nextLine();

for(int i = 0; i < arrayString.length; i++){
    if(name.equals(arrayString[i])) {
        System.out.println(arrayReal[i]);
    }
}

Solution with a HashMap

  1. Initialize HashMap

    HashMap<String, Double> hm = new HashMap<String, Double>();

  2. Fill HashMap

    hm.put("Christopher Lee", 54.0);

  3. Print double value of student

    System.out.print("Please enter name of student: "); String name = sc.nextLine(); System.out.println(hm.get(name));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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