Solved

How to use DecimalFormat

Posted on 2004-09-12
8
1,022 Views
Last Modified: 2010-08-05
I'm a new programming student...this is an assignment so I really need guidance or suggestions on how to make it work correctly.

I have the below code that provides conversion for a selected currency. I need to format the results with two decimal places. I think the DecimalFormat class is need somehow but I am not sure exactly where to insert the class. I tried inserting within the switch statements but keep getting an unreachable statement error (really not sure what that means).

import java.io.*;                  // required for BufferedReader


//gives my Java program the name Currency_wj
class Currency_wj {
      
      //the main part of the program begins here      
      public static void main(String[] arguments) throws Exception {
      
      //"throws Exception",
      //throws Exception needed when reading
      //from keyboard. Says you will take
      //responsibility for errors.
      

      //reads selection number from menu entered by user
      BufferedReader      br = new BufferedReader(
      new InputStreamReader(System.in));
      
      //reads amount entered by user
      BufferedReader money = new BufferedReader(
      new InputStreamReader(System.in));
                                    
      double ArgentinaCurrency = 2.95;  //declare and initialize  
      double CanadaCurrency = 1.32;       //declare and initialize
      double calculate = 0.00;            
      String cname1 = "Argentina Peso";  //declare and initialize string
      String cname2 = "\nCanada Dollar"; //declare and initialize string
      String cnames = cname1.concat(cname2); //concatenate two Strings
      String intro = "Welcome to the "; //declare and initialize String
      String name = "Currency Exchange Program!"; //declare and initialize String
      String title = intro.concat(name); //concatenate two Strings
      double dollar; //delcare and initialize
            
      //display combination of concatenated string             
      System.out.println(title + "\n\nThe currency exchange program shows\n"+
      "the exchange rate of $1 American dollar\n" +
      "for the following currencies:\n\n" + cnames);      
            
      // prints a blank line
      System.out.println();
            
      //display current currency rates
      System.out.println(cname1 + " = " + ArgentinaCurrency + cname2 + " = " +  CanadaCurrency);
            
      //prints a blank line
      System.out.println();
            
            
      char keep_going = ' ';          // initialize, set initial value
      String inString;            //declare
      char MenuChoice;            //delcare
      dollar = 0.00;            //declare and set initial value
      double amount = 0.0;      //delcare and set initial value
      String data = "oo";            //
      

      while (keep_going != 'q')       // will continue loop until condition met
      {
            //displays to screen statement in quotes
            System.out.println("\nSelect a currency to convert:\n");
            System.out.println("      1. Argentina Pesos");
            System.out.println("      2. Canada Dollars");
            System.out.println("      3. Exit.");    
                                       

            // Send all output to the monitor and make the
            // cursor visible before the user begins typing.
            System.out.flush();
            
            // "readline()" returns a String which is
            // assigned to a String variable, inString
            inString = br.readLine();
            
            MenuChoice = inString.charAt(0);
            // get first char of String
                                       
            
            //switch case statement, displays data to screen depending on user selection
            switch(MenuChoice)
            {
                  case '1':           
                  //displays data in quotes to screen      
                  System.out.println("You want to convert Argentina Pesos");
                        
                  //displays data in quotes to screen
                  System.out.print("Enter dollar amount to convert: ");
                        
                  //displays data and displays cursor
                  System.out.flush();
                        
                  //stores amount entered by user
                  data = money.readLine();
                        
                  //converts string to double
                  amount = Double.parseDouble(data);
                         
                  //displays amount entered, currency name, calculates conversion and  displays results
      System.out.println(amount + " Argentina Pesos equal " + amount*ArgentinaCurrency + " American Dollars");
      break;
                                    
                            case '2':
                  //displays data in quotes to screen
                  System.out.println("You want to convert Canada Dollars");
                        
                  //displays data in quotes to screen
                  System.out.print("Enter dollar amount to convert: ");
                        
                  //displays data and displays cursor
                  System.out.flush();
                        
                  //stores amount entered by user
                  data = money.readLine();
                        
                  //converts string to double
                  amount = Double.parseDouble(data);
                        
                  //displays amount entered, currency name, calculates conversion and displays results
                  System.out.println(amount + " Canada Dollars equal " + amount*CanadaCurrency + " American Dollars");
                  break;                  
                        
                  case '3':
                  //condition met -- program exits
                  keep_going = 'q';
                  break;
                  
                  default:
                  //displays data to screen when invalid entry entered
                  System.out.println("You entered an invalid number, please enter 1-3");                  break;
                        
            } // end switch
      }      // end while


      //displays data in quotes to screen      
      System.out.print("\nThank you for using the Currency Exchange Program\n");
      
      
            
            }//end main
      }//end class




Any suggestions would be greatly appreciated.
0
Comment
Question by:contesa
  • 2
  • 2
  • 2
  • +2
8 Comments
 
LVL 92

Assisted Solution

by:objects
objects earned 150 total points
Comment Utility
create a format like so:

DecimalFormat df = new DecimalFormat("0.00");

and then use it:

System.out.println(amount + " Canada Dollars equal " + df.format(amount*CanadaCurrency) + " American Dollars");
0
 

Accepted Solution

by:
Emilda earned 150 total points
Comment Utility
Include the below statements in your program just before printing the converted values. You can restrict to two decimal places using the format given by the variable myFormat.

Hope this helps.

amount = amount*ArgentinaCurrency;
String myFormat = "#.00";
DecimalFormat df = new DecimalFormat(myFormat);            
String result = df.format(amount);
                     
//displays amount entered, currency name, calculates conversion and  displays results
System.out.println(amount + " Argentina Pesos equal " + result + " American Dollars");
break;
0
 
LVL 16

Assisted Solution

by:suprapto45
suprapto45 earned 200 total points
Comment Utility
Hi contesa,

Emilda is right,

add these codes...

String myFormat = "#.00";
DecimalFormat df = new DecimalFormat(myFormat);
               //displays amount entered, currency name, calculates conversion and  displays results
     System.out.println(amount + " Argentina Pesos equal " + df.format(amount*ArgentinaCurrency) + " American Dollars");
     break;

and not forgetting to

import java.text.*;

Thanks and I hope that helps. Remember object and Emilda who helped you.
0
 
LVL 6

Expert Comment

by:expertmb
Comment Utility
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:contesa
Comment Utility
You guys are awesome...thank you.

/contesa

0
 
LVL 92

Expert Comment

by:objects
Comment Utility
no worries :)
0
 

Expert Comment

by:Emilda
Comment Utility
:-)

Thank you.
0
 
LVL 16

Expert Comment

by:suprapto45
Comment Utility
:)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mergeTwo  challenge 13 71
Securing Jmx Console and web console 2 45
backtracking recursion  code 19 39
eclipse formatting 6 38
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now