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
what about
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
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
This will help you progress further.
Hope this helps.
First, you will want to initialize
i
to0
when you declare it:Then, after splitting the line you can pull the data out of the
String[]
and put it in yournames
andscores
arrays: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 tosplit()
. Also keep in mind thatInteger.parseInt()
can throw aNumberFormatException
if it is not able to parse the data in the scores column as an integer.