/* WinLoss.java -- ask the user for wins and losses, and calculate percent * of matches that were won. Assume there are no ties. Here we practice * two very important built-in classes for I/O: StringTokenizer to help us * when reading input, and NumberFormat for printing output. */ import java.io.*; // include I/O import java.util.*; // include string tokenizer class import java.text.*; // include number format class public class WinLoss { public static void main(String [] args) throws IOException { // ---------------------------------------------- // input: Ask the user for the win-loss record. // ---------------------------------------------- BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter win-loss record (e.g. 15-7): "); String input = kbd.readLine(); // ----------------------------------------------------------------- // We create a StringTokenizer object called "tok" that keeps track // of where we are in a String. The string tokenizer needs to know // what string to read from, and also what character(s) to ignore: // In this case we want to ignore spaces and the hyphen. // ----------------------------------------------------------------- StringTokenizer tok = new StringTokenizer(input, "- "); // ------------------------------------------------------ // Use the nextToken() function to separate the numbers. // ------------------------------------------------------ int wins = Integer.parseInt(tok.nextToken()); int losses = Integer.parseInt(tok.nextToken()); // ------------------------------------- // the calculation is straightforward... // ------------------------------------- double percent = 100.0 * wins / (wins + losses); // --------------------------------------------------------------- // Output the winning percentage -- to exactly 1 decimal place // We create a NumberFormat object called "formatter" that stores // information about how to format a number. This is very similar // to the example on pp. 109-110 in the book. Finally, we use // the format() function, which creates a String containing the // formatted number. // --------------------------------------------------------------- NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(1); formatter.setMinimumFractionDigits(1); String expression = formatter.format(percent); System.out.println("Your winning percentage is " + expression + "%"); } }