// Format.java // Solution to Short Assignment #3 by THC. // Asks the user for a number x and a number of decimal places. // Prints the square of x to the requested number of decimal places, // with trailing 0s trimmed off. // Note: You can ask for as many places as you like, but the // DecimalFormat class will cut you off at 16 places. Also, if // you ask for a negative number of decimal places, you get 0 places. import java.util.Scanner; import java.text.DecimalFormat; public class Format { public static void main(String[] args) { double x; // number to take square of int places; // how many decimal places // Create a Scanner for keyboard input. Scanner input = new Scanner(System.in); // Get the number to take the square of from the user. System.out.print("What number do you want the square of? "); x = input.nextDouble(); // Now find out how many decimal places. System.out.print("How many decimal places? "); places = input.nextInt(); // Starting with a pattern of "0.", append a "#" for each decimal // place that the user has asked for. // We use a for loop here, but we could just as well have used // a while loop. String pattern = "0."; for (int i = 1; i <= places; i++) pattern = pattern + "#"; // Now pattern is "0." followed by places "#" symbols. // Make a DecimalFormat object fmt that uses this pattern. DecimalFormat fmt = new DecimalFormat(pattern); // Print out the result, using the format now contained in fmt. // We can just use x * x as the parameter to fmt.format, since that // parameter is supposed to be any double. System.out.println("To " + places + " decimal places, " + x + " squared = " + fmt.format(x * x)); } }