Witajcie ....Czy mial by ktos chec pomoc mi lub podpowiedziec (przykladem) .Jak zrobic zeby ten program ostrzegal mnei ze w pliku tekstowym brakuje czesci danych np.Mam plik w ktorym sa zapisane wyniki meczow w formacie .....team A : Team B : wynik A : wynik b....Udalo mi sie zrobic wyjatek jak nie ma pliku w ogole ale jak zrobic jesli na przyklad w pliku brakuje ktorejs druzyny lub wyniku w tej linijce czy tez tego separatora ktorym jest w tym przypadku dwukropek...Jestem w kropce nie wiem gdzie to zaczac .Probowalem uwzglednic If (splitArray[0] == " ") ale nie dzialalo ...pomoze ktos :musze uwzgednic bledy gdy nie ma druzyny a lub b ,gdy nie ma wyniku a lub b ,gdy separator jest inny ,badz jesli wyniki nie sa Intami.Dzieki za kazda pomoc
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
//A list to add results to, so they can be printed out after the parsing has been completed.
ArrayList<LineResult> results = new ArrayList<>();
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();// Read a line of data from text file
// this if statement helps to skip empty lines
if (line == "") {
continue;
}
String [] splitArray = line.split(":");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
//TODO: REQ3: Validate inputs better
if (splitArray[0] != splitArray[0].trim())
System.out.println("error");
try {
// Extract each item into an appropriate variable
LineResult result = new LineResult();
result.homeTeam = splitArray[0];
result.awayTeam = splitArray[1];
result.homeScore = Integer.parseInt(splitArray[2]);
result.awayScore = Integer.parseInt(splitArray[3]);
results.add(result);
} catch(NumberFormatException e) {
System.out.println("Error: Cannot convert to number");
}
}
}
//Print out results
System.out.println("Home team Score Away team Score");
System.out.println("========= ===== ========= =====");
//Loop through each result printing out the required values.
//TODO: REQ4, filter results based on user requested team
for (LineResult result : results) {
System.out.println(
String.format("%-15s %3s %-15s %3s",
result.homeTeam,
result.homeScore,
result.awayTeam,
result.awayScore));
}
// end of try block
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
//Data object for holding a line result
static class LineResult {
String homeTeam, awayTeam;
int homeScore, awayScore;}
}