Domanda

I am writing a program that reads through a file of various types of data. I am trying pass in the data from the file, to various arrays that I have created.

Sample portion from file (double spaced for line breaks. White spaces between categories are tabs, but white space between first/last names and countries are spaces)

Name Age    Country Year    Closing Date    Sport   Gold    Silver  Bronze  Total

Joe Max 24  Algeria 2012    8/12/2012   Athletics   1   0   0   1

Tom Lan 27  United States   2008    8/24/2008   Rowing  0   1   0   1

When my code compiles, however, I get the InputMismatchException. I am wondering if it deals with the fact that at the end of each line, there is no tab that ensues. Can anyone help me through this?

public static void main(String[] args) {
Scanner console = new Scanner(System.in);
intro();

Scanner input1 = null;
Scanner input2 = null;
int lineCount = 0;

try {
    input1 = new Scanner(new File("olympicstest.txt"));

} 
catch (FileNotFoundException e) {
    System.out.println("Invalid Option");
    System.exit(1);
}

while (input1.hasNextLine()) {
    lineCount++;
    input1.nextLine();
}

lineCount = lineCount - 1;

String[] country = new String[lineCount];
int[] totalMedals = new int[lineCount];
String[] name = new String[lineCount];
int[] age = new int[lineCount];
int[] year = new int[lineCount];
String[] sport = new String[lineCount];

try {
    input2 = new Scanner(new File("olympicstest.txt"));
    input2.useDelimiter("\t");  
} 
catch (FileNotFoundException e) {
    System.out.println("Invalid Option");  // not sure if this line is needed
    System.exit(1);  // not sure if this line is needed
}        

String lineDiscard = input2.nextLine();
for (int i = 0; i < lineCount; i++) {
    name[i] = input2.next();
    age[i] = input2.nextInt();
    country[i] = input2.next();
    year[i] = input2.nextInt();
    input2.next();  // closing ceremony date
    sport[i] = input2.next(); 
    input2.nextInt();  // gold medals
    input2.nextInt();  // silver medals
    input2.nextInt();  // bronze medals
    totalMedals[i] = input2.nextInt();
}

}
È stato utile?

Soluzione

yes when you set a specific delimiter, unfortunately that becomes the only delimiter used to separate values which don't play nicely with your .next() statements, so you can either add tabs (\t) to the end of each line or you can set both \t and \n to delimiters with regex "[\t\n]". I also prefer to use CSV format, and separate all values with commas because tabs and whitespace characters often aren't very distinguishable from a visual standpoint so I've found it is easier to use/format later on

Altri suggerimenti

Yes, you're right about what's causing the problem. A solution would be to use a regex in the useDelimiter call that accepts both tabs and linebreaks. So you would do:

input2.useDelimiter("[\t\n]");

Explanation of the regex

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top