I just have a couple quick questions regarding reading a text file in Java. I am
ID: 3770739 • Letter: I
Question
I just have a couple quick questions regarding reading a text file in Java. I am trying to read names of teams from a list along with how many championships they have won. I am storing the information into a binary search tree. My text file will be in this format:
Notre Dame (22)
Syracuse (1)
Michigan (16)
Navy
Alabama (19)
Iowa (4)
Michigan State (6)
It can assumed that the text file will always be in this format. Each line will list a team, followed by one or more spaces, and then the number of championships in parenthesis. If a line does not have a number or parenthesis, it can be assumed that they have one championship. What is the best way to read the file line by line, storing the letters in a String, and then only the number in an int? I do not care about adding the data to a binary search tree at this point. I will just print out the data as it is scanned in onto the console. Thank you in advance for your help!
Explanation / Answer
package assignment;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ChampDataInFile {
public static void main(String[] args) {
String inputFile = "D:/ravi/Cheg/championships.txt";
try {
Scanner sc = new Scanner(new File(inputFile));
String str = null;
String tokens[] = null;
int noOfchmps = 0;
String champ = null;
while (sc.hasNext()) {
str = sc.nextLine();
if (str != null && !"".equals(str.trim())) {
if(str.contains("(")) {
tokens = str.split("\(");
if (tokens != null) {
champ = tokens[0].trim();
//parse string in tokens(1) get number
noOfchmps = Integer.parseInt(tokens[1].substring(0, tokens[1].indexOf(")")));
}
} else {
champ = str.trim();
noOfchmps = 1;
}
System.out.println("Champion: "+champ+" No of championships won: "+noOfchmps);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
----output-----
Champion: Notre Dame No of championships won: 22
Champion: Syracuse No of championships won: 1
Champion: Michigan No of championships won: 16
Champion: Navy No of championships won: 1
Champion: Alabama No of championships won: 19
Champion: Iowa No of championships won: 4
Champion: Michigan State No of championships won: 6