Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

How to use DecimalFormat

Posted on 2004-09-12
8
1,026 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
ID: 12040642
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
ID: 12040816
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
ID: 12041138
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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 6

Expert Comment

by:expertmb
ID: 12041222
0
 

Author Comment

by:contesa
ID: 12050788
You guys are awesome...thank you.

/contesa

0
 
LVL 92

Expert Comment

by:objects
ID: 12050822
no worries :)
0
 

Expert Comment

by:Emilda
ID: 12050890
:-)

Thank you.
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 12054997
:)
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
expectj telnet failing 5 45
Configure a Bean in an XML file 4 42
Is Applet the way to go for my drag and drop system? 8 25
Java syntax, or is it Selenium 6 30
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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.

789 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