/* WinLoss.java * Read a file that contains some win-loss records, * and calculate the percentage of games won for each season. * Let's assume there are no ties or overtime losses. * Each line of the input file will look like num-num (e.g. 13-8). * Let's also compute the OVERALL win-loss record. * Note: to print a '%' in printf, you need to say %%. */ import java.util.Scanner; // for input import java.io.FileInputStream; // for reading files import java.io.FileNotFoundException; // in case file doesn't exist! public class WinLoss { public static void main(String [] args) throws FileNotFoundException { Scanner inFile = new Scanner(new FileInputStream("winloss.in")); // Keep track of total number of wins and losses. int totalWins = 0; int totalLosses = 0; // Keep reading lines until there's no more input. while(inFile.hasNext()) { String line = inFile.next(); // This line has 2 numbers separated by a hyphen. We need to // extract the 2 numbers. There's more than one way to do this. // Let's practice our String functions: // find the location of the hyphen, and use substring to // find the 2 numbers. // However, we'll still need to convert from String to integer. // For example to convert "12" to the number 12. // To to this, we'll use Integer.parseInt ( string parameter ) int hyphenLocation = line.indexOf('-'); String winString = line.substring(0, hyphenLocation); String lossString = line.substring(hyphenLocation + 1); int wins = Integer.parseInt(winString); int losses = Integer.parseInt(lossString); int games = wins + losses; // Now we know the number of wins and losses for this season. // 1. Compute and print the percentage of wins. // 2. Keep track of total wins and losses. double percent = 100.0 * wins / games; System.out.printf("%d-%d winning percentage %4.1f%%\n", wins, losses, percent); totalWins = totalWins + wins; totalLosses = totalLosses + losses; } // Now we know the total record of total wins and losses. // Need to calculate OVERALL winning percentage too. int totalGames = totalWins + totalLosses; double overallPercent = 100.0 * totalWins / totalGames; System.out.printf("\n%d-%d overall record, percentage is %4.1f%%\n", totalWins, totalLosses, overallPercent); } }