Exception, Unicode and Double checking and printing Exercise
Reminders:
DecimalFormatter object knows: How to print decimals
Package to import: import java.text.DecimalFormat;
How to create a DecimalFormatter for your numbers:
DecimalFormat percentage2 = new DecimalFormat(0.00%);
How to use a DecimalFormatter to print to your screen:
System.out.println(percentage2.format(.308)); // will print 30.80%
Different format options:
0 = required position
# = show it if you have it
% = make it a % (mult by 100)
E = E notation (scientific)
Try/Catch:
Try{}
Catch{}-------------------------------------------------------------------------------------------------------
ANSWER
-------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.text.DecimalFormat;
public class workwithException
{
public static void main(){
Scanner myman = new Scanner(System.in);
DecimalFormat twoplaces = new DecimalFormat("0.00");
System.out.println("Please enter a number");
try {
int x = myman.nextInt();
System.out.println("The number " + x + " in unicode represents the char "
+ (char)x);
double new1 = x/3.; // x = 5 will cause mismatch
new1 = new1/3.;
new1 = new1/3.;
new1 = new1*27;
if (new1 == x)
{
System.out.println ("It matches exactly");
}
else
{
System.out.println("No exact Match x = " + x + " and new1 = " + new1);
if (Math.abs(x-new1)< .001)
{System.out.println ("It matches within .001");
}
else
{
System.out.println ("Still no match within .001");
}
}
System.out.println("The decimal formatted is " + twoplaces.format(new1));
}
catch (Exception e)
{
System.out.println("You did not enter an integer");
}
}
}