Reading a file and storing names and numbers in two arrays

落爺英雄遲暮 提交于 2019-12-31 07:00:28

问题


I'm working on a program that reads a file and stores the names and scores in two separate arrays, but I'm struggling. This is what I have so far. I created an array for names called names, but I'm confused how I would copy the names into each index of the array.

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

public class ScannerReadFileSplit {
     public static void main(String[] args) {

File file = new File("NamesScore.txt");
String[] names = new String[100];
int[] scores = new int[100];
int i;

 try {
      Scanner scanner = new Scanner(file);
      while (scanner.hasNextLine()) {
         String line = scanner.nextLine();
         String [] words = line.split("\t");
         for (String word: words) {
            System.out.println(word);
         }
       }
  } catch (FileNotFoundException e) {
     e.printStackTrace();
  }
 }
}

My text file is:

John James      60
Kim Parker      80
Peter Dull      70
Bruce Time      20
Steve Dam       90

回答1:


First, you will want to initialize i to 0 when you declare it:

int i = 0;

Then, after splitting the line you can pull the data out of the String[] and put it in your names and scores arrays:

String [] words = line.split("\t");

// The first element in 'words' is the name
names[i] = words[0];

// The second element in 'words' is a score, but it is a String so we have
// to convert it to an integer before storing it
scores[i] = Integer.parseInt(words[1], 10);

// Increment 'i' before moving on to the next line in our file
i++;

Don't forget to increment i as shown above.

There is some error checking that I have glossed over. You will probably want to check that words has a length of 2 after your call to split(). Also keep in mind that Integer.parseInt() can throw a NumberFormatException if it is not able to parse the data in the scores column as an integer.




回答2:


I have tried to correct your code and provided inline comments where I felt you have went wrong. Actually you were close to the solution. Try to figure out what you are getting as an output after a line of code like

String[] words = line.split("\t");

This line will give two String(as it will split the line in your file which has only one tab separated name and score). And you can try to debug by yourself. Like simply printing the value. for example

System.out.println(words[0]);

This will help you progress further.

Hope this helps.

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

public class TwoArrays {
    public static void main(String[] args) {
        File file = new File("C:\\test\\textTest.txt");
        String[] names = new String[100];
        int[] scores = new int[100];
        int i = 0;
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] words = line.split("\t");
                names[i] = words[0]; // storing value in the first array
                scores[i] = Integer.parseInt(words[1]); // storing value in the
                                                        // second array
                i++;
            }
            /*
             * This piece of code will give unnecessary values as you have
             * selected an array of size greater than the values in the file for
             * 
             * for(String name: names) { 
             *      System.out.println("Name:- "+name);
             * }
             * for(int score: scores) { 
             *      System.out.println("Score:- "+score);
             *  }
             */
            // Better use the below way, here i am restricting the iteration till i
            // i is actually the count of lines your file have.
            for (int j = 0; j < i; j++) {
                System.out.println("Name:- " + names[j] + "\t" + "Score:- " + scores[j]);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}



回答3:


what about

  int l = 0;  
  while (scanner.hasNextLine()) {
     String line = scanner.nextLine();
     String [] words = line.split("\t");
     names[l] = words[0];
     scores[l] = Integer.parseInt(words[1]);
     System.out.println(l + " - name: " + names[l] + ", score: " + scores[l]);
     l++; 
   }


来源:https://stackoverflow.com/questions/41622937/reading-a-file-and-storing-names-and-numbers-in-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!