Class 1, Part 2 | Intro to Java 30-IT-396 |
Example: Formatting Output
/*
* FormatMe.java
*
* Created on January 14, 2002, 12:30 AM
*/
// Import the NumberFormat class so that we can use it below.
import java.text.NumberFormat;
// Import the swing package so that we can prompt the user.
import javax.swing.JOptionPane;
/**
* FormatMe
*
* Show use of formatting output.
*
* @author jonesbr@email.uc.edu
*/
public class FormatMe {
/** Creates a new instance of FormatMe */
public FormatMe() {
}
public void promptUser() {
// Wrap in a try-catch
block.
try {
// Prompt the user for a number.
String strNumber = JOptionPane.showInputDialog("Give me a number.");
// Convert the string input to a double by using the static parseDouble()
// method of the Double class.
double dblNumber = Double.parseDouble(strNumber);
// Create some NumberFormat instances.
NumberFormat altNumber = NumberFormat.getNumberInstance();
altNumber.setMaximumFractionDigits(5);
altNumber.setMinimumFractionDigits(3);
NumberFormat normalNumber = NumberFormat.getNumberInstance();
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
// Print the results to standard output.
System.out.println("Number with fraction digits range 3-5: " + altNumber.format(dblNumber));
System.out.println("Number with no restrictions: " + normalNumber.format(dblNumber));
System.out.println("Number as currency: " + currency.format(dblNumber));
System.out.println("Number as percentage: " + percent.format(dblNumber));
// Catch number format
error, try again.
} catch (NumberFormatException
e) {
System.out.println("Idiot. I said enter a number. Try again.");
promptUser();
}
}
/**
* Instantiates new FormatMe from user
input.
*
*/
public static void main(String args[]) {
FormatMe formatMe =
new FormatMe();
formatMe.promptUser();
}
}
Created by: Brandan
Jones January 4, 2002