I have an assignment for school...Write a program CurrencyCOnverter that asks the user to enter today's price of one dollar in euro. THen the program reads U.S. dollar values and converts each to euro values. I have the following code. It works great until I start putting the loops and then it keeps giving me an answer of zero.

public class CurrencyConverter
{
	private double dollars;
	private double euros;
	private double exchangeRate;
	
	public CurrencyConverter()
	{
		dollars = 0.0;
		exchangeRate = 0.0;
	}

	public double getDollars()
	{
		return dollars;
	}
	
	public double getExchangeRate()
	{
		return exchangeRate;
	}
	
	public double getEuros()
	{
		euros = dollars * exchangeRate;
		return euros;

	}
	}
import java.util.Scanner;

public class CurrencyConverterTester
{
	
   public static void main(String[] args)
   {
	   Scanner in = new Scanner(System.in);
	   CurrencyConverter converter = new CurrencyConverter();
	   
	   boolean done = false;
	      while (!done)
	      {  
	         System.out.print("Enter dollar amount, -1 to quit: ");
	         double dollars = in.nextDouble(); 
	         if (dollars != -1)
	         {
	            done = false;
	         System.out.print("Enter the exchange rate: ");
	         double exchangeRate = in.nextDouble();         

	         
	         System.out.println(dollars + " dollars = " + converter.getEuros() + " euros");
	         }

	         else
	         {  
	            done = true;
	         }
	      }
     }

   }

Recommended Answers

All 2 Replies

You have declare and initialize "converter" variable outside the loop. And then, you didn't assign any value to the variable but use it right away. As a result, the value inside the variable is only whatever it is initialized - 0.

What you can do are 2 ways, either keep initializing a new converter object and get the computation, or you add methods to set the object's dollars & exchangerate variables. Either way, you need to modify your CurrencyConverter class. For the first way, you need to add a new constructor, and you could move your line 9 inside the while loop right below line 20. If you do the latter, you need to add either 1 or 2 methods to accept the variables "dollars" and "exchangeRate" inside the loop... Pick one :)

Thank you so much! I used the first method and everything is working great now. I know you have answered many of my posts so thank you for being so helpful. I am in school for Programming and taking classes online and it has been wonderful to have a great resource to get some help. Many of the answers are posted somewhere online but I am one who likes to be able to figure it out and to ask a question once I've given it an attempt so I can actually understand what is going on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.