Solved

How to use DecimalFormat

Posted on 2004-09-12
8
1,033 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
[X]
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
  • 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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
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

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

729 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