I can't get the object array in lab9 class (named "thelist") to be populated with objects from the Foreign class. please see line 35 in lab9 class. I've tried using toString, useing a Foreign type variable as a parameter in a addData(), a addData() method ect... I am really really stuck. I am just learning Java and there are no Tutors available at my school. Thank you in advance for any help, ideas, or solution in advance. These two classes compile but they dont work.
I've spent two weeks trying to analyze and learn how to do the step on line 35 and I have hit a brick wall, I just can not figure out why the things I have tried didn't work. I really want to learn how to do this.
Theses are the instructions for the homework assignment:

Modify your prior Lab 8 by adding an array of objects. Within the loop, instantiate each individual object. Make sure the user cannot keep adding another Foreign conversion beyond your array size.
After the user selects quit from the menu, prompt if the user want to display a summary report. If they select ‘Y’ then, using your array of objects, display the following report:

Item Conversion Dollars Amount
1 Japanese Yen 100.00 32,000.00
2 Mexican Peso 400.00 56,000.00
3 Canadian Dollar 100.00 156.00
etc.

Number of Conversions = 3
=======================================================
here are the two classes I wrote for this assignment
=======================================================

import java.util.Scanner;
     
    public class lab9
    {
        public static void main(String[] args)
        {
            
				final int Max = 10;
				int choice;
				
            String s;     
            char c; //choice for summary report
            int i = 0;
				Foreign foreignObject = new Foreign();                
				Foreign[] thelist = new Foreign[Max];//array of 10 reference variables of type "Foreign"   
				Scanner Keyboard =new Scanner(System.in);               
            Foreign.title();  
				
				do
            	{
                              
										 Foreign.menu();
					  					
										choice=Foreign.number;//gets choice number entered for choice
						  					 
					 			if(i < thelist.length)
					 						
									{
										 thelist[i] = new Foreign();//gives actual reference to memory large enough for a object of Foreign class
																				 
										 thelist[i]. getDollars();//can't get method or to toString to populate thelist object array
										 
										 i++;
										
										 foreignObject.vertical();
					 					  										  
								    }
                                      
							  
							   
            
            }while (choice != 0 && i <= Max );
				
				System.out.print("\t\t\nWould you like to display a summary report? (y/n): ");
      		
				s = Keyboard.nextLine();
		 
     			c = s.charAt(0);
            
				 switch (c)
               {
               case 'y':
               case 'Y':
                 System.out.println("\nItem\t\tConversion\t\tDollars\t\tAmount");

                 for ( i = 0 ; i < thelist.length ; i++)
					    { 
					      System.out.println(i+1 + "\t");

										 
					      System.out.print(thelist[i] + "\t");
                            
                   }
             }
             
            foreignObject.counter();
        }
    }


//======================================================================================//================================================



import java.util.Scanner;
import java.text.*;
 
 public class Foreign
    {
      public static int number;//number entered for choice
    	public static int n;
	 	private static int count = 0;//count of the number conversions made
		private double dollars, amount;
		public static double rate;
	   public static String country ;
		public static String[] cName= {"","Canadian Dollars","Mexican Peso","Japanese Yen","Euros"};
    	public static double[] rates= {0,1.03,10.55,117.57,.8407};//0 and "" so index "i" matches number 1 choice
	   DecimalFormat rF = new DecimalFormat("##00.##");	
	   DecimalFormat money = new DecimalFormat("###,###,#00.##");
		static Scanner read=new Scanner(System.in);
	
     
    public Foreign()// constructor to initialize numerics to 0 and country to "" null

    {
    
	    country = "  ";
		 number=0;
		 rate = 0.0;
		 amount = 0.0 ;
		 dollars = 0.0;  

	      }
     
    public static void title()// a static method to display title

      {  
		System.out.println("\t\tForeign Exchange\n\n");
		}
     
        public static void menu()
        {
        		System.out.println("\t\t1. U.S. to Canadian Dollars");
	     		System.out.println("\t\t2. U.S. to Mexican Pesos"); 
	     		System.out.println("\t\t3. U.S. to Japanese Yen"); 
	     		System.out.println("\t\t4. U.S. to European Euros"); 
	     		System.out.println("\t\t0. Quit\n\n"); 
				System.out.println("\t\tEnter your choice: "); 
        		
				
				
				do
				{ 
						n = read.nextInt();
						if (n > 4 || n < 0)
				 		
						System.out.println("\t\tPlease enter 1 through 4 or 0 to quit:\n");
									
				
				
				}while (n > 4 || n < 0);
											
				
				number = n	;
       		
				country = cName [number];
				
				rate=rates[number];

		 
		  }  
		 
		  public void getDollars()
			
			{
				 				
				   System.out.print("\t\tPlease enter amount in U.S. dollars:\n");
	   		  
				   Scanner input = new Scanner(System.in);
		  	  		
					dollars = input.nextDouble();
					
					count++;
              
               amount=dollars*rate;

			}
		  
		  
		  
	     
    public void vertical()
    			{

    			System.out.println("\t\tCountry = " + country );
				System.out.println("\t\tRate = " + rF.format(rate) );
				System.out.println("\t\tDollars = " + money.format(dollars) );
				System.out.println("\t\tValue = " + money.format(amount) );
    }
     
     
   public String toString()   //a toString()method to display the data horizontally via a string returned to lab9

	
			{
		   		 
		 	 String line;	
		 		
			 line = "\n\n" + country +  "\t\t " + money.format(dollars) + "\t\t " + money.format(amount)+"\n\n";
		 		
			 return line;
			 
			 }
	
    public  void counter()
    		{
			
			System.out.println("\nThe total number conversions made is " + count);
    		
			}
	
	
	
}

Recommended Answers

All 12 Replies

I can't get the object array in lab9 class (named "thelist") to be populated with objects from the Foreign class

Please explain. If you get errors, copy the full text of the error messages and paste them here.

So you're trying to add a foreign object to an array of this type?
How about "thelist[0] = foreignObject; " and then just use a counter to add to the next index every time?

So you're trying to add a foreign object to an array of this type?
How about "thelist[0] = foreignObject; " and then just use a counter to add to the next index every time?

In the Foreign class there are two arrays , named cName (each country's curency name i.e. Mexican Peso, Canadian Dollars...) and rates (exchange rate for each country's curency). The arrays have the same number of elements as the menu choices for exchange conversions in the Menu(). We use the menu choice as the element number for accessing the appropriate values from the two arrays. We then wrote code to get dollars and the conversion amounts. In the last lab the values that we used in the conversions were just printed with each conversion with a call to both the "print" vertical()and a toString() methods that was easy. In this lab9 we add an array of objects and within the loop, instantiate each individual object. I tried to follow an example the prof gave us. In my Foreign class getDollars() method I have the code that develops the values for the report. I think the values are suposed to be the object that is loaded during each conversion into the thelist array in the lab9 class(in the loop)and then if the user says yes a summary report is printed.
Your sugestion makes more sense to me but I don't know how to go about getting thelist array populated and/or do I have the code to print the summary report wrong?
Here is the output of my code :


Foreign Exchange


1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
1
Please enter amount in U.S. dollars:
1
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
2
Please enter amount in U.S. dollars:
2
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
3
Please enter amount in U.S. dollars:
3
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
0
Please enter amount in U.S. dollars:
0
Country =
Rate = 00
Dollars = 00
Value = 00

Would you like to display a summary report? (y/n): y

Item Conversion Dollars Amount
5


01 00

5


02 00

5


03 00

5


00 00


The total number conversions made is 4

----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.

So you're trying to add a foreign object to an array of this type?
How about "thelist[0] = foreignObject; " and then just use a counter to add to the next index every time?

In the Foreign class there are two arrays , named cName (each country's curency name i.e. Mexican Peso, Canadian Dollars...) and rates (exchange rate for each country's curency). The arrays have the same number of elements as the menu choices for exchange conversions in the Menu(). We use the menu choice as the element number for accessing the appropriate values from the two arrays. We then wrote code to get dollars and the conversion amounts. In the last lab the values that we used in the conversions were just printed with each conversion with a call to both the "print" vertical()and a toString() methods that was easy. In this lab9 we add an array of objects and within the loop, instantiate each individual object. I tried to follow an example the prof gave us. In my Foreign class getDollars() method I have the code that develops the values for the report. I think the values are suposed to be the object that is loaded during each conversion into the thelist array in the lab9 class(in the loop)and then if the user says yes a summary report is printed.
Your sugestion makes more sense to me but I don't know how to go about getting thelist array populated and/or do I have the code to print the summary report wrong?
Here is the output of my code :


Foreign Exchange


1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
1
Please enter amount in U.S. dollars:
1
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
2
Please enter amount in U.S. dollars:
2
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
3
Please enter amount in U.S. dollars:
3
Country =
Rate = 00
Dollars = 00
Value = 00
1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
0
Please enter amount in U.S. dollars:
0
Country =
Rate = 00
Dollars = 00
Value = 00

Would you like to display a summary report? (y/n): y

Item Conversion Dollars Amount
5


01 00

5


02 00

5


03 00

5


00 00


The total number conversions made is 4

----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.

Where in your code do you assign a value to rate? It looks like it is always zero.
Make sure the code is executing where you think it is getting a value by putting a println statement right after it is given a value to print out the value of the rate variable.

The same with the country variable. Where does it get a value? Are you sure it is assigned a value other than ""?

At the end of your last post there are a lot of lose numbers. What are they?
When you print a number, put a String with it to give it a label. For example:
System.out.println("rate=" + rate);

One of your big problems is using static variables and methods.
You need to get rid of ALL usages of static in the Foreign class if you are going to create more that one instance of the class.

Where in your code do you assign a value to rate? It looks like it is always zero.
Make sure the code is executing where you think it is getting a value by putting a println statement right after it is given a value to print out the value of the rate variable.

The same with the country variable. Where does it get a value? Are you sure it is assigned a value other than ""?

At the end of your last post there are a lot of lose numbers. What are they?
When you print a number, put a String with it to give it a label. For example:
System.out.println("rate=" + rate);

rate and country curency name get assign in the menu() of the Foreign class. They are in the menu() method but not in the getDollars() method. They are both static and so are both of the arrays , shouldn't they be available to all the methods in the Foreign class including the getDollars() method? The arrays in the Foreign class are working but I don't know why the two static variables are not available to the getDollars() method in the Foreign class.

here's the output of my code:
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
2
This is in menu() rate = 10.55country = Mexican Peso
Please enter amount in U.S. dollars:
2
this is in getDollars()rate = 0.0country = amount = 0.0
Country =
Rate = 00
Dollars = 00
Value = 00

One of your big problems is using static variables and methods.
You need to get rid of ALL usages of static in the Foreign class if you are going to create more that one instance of the class.

I removed static from the variables and methods in the Foreign class. It did not change anything the result was the same. The statics were there from a previous lab but your probably right I should have removed them.
Here's part of the output:


Enter your choice:
2
This is in menu(): rate = 10.55 country = Mexican Peso
Please enter amount in U.S. dollars:
3
this is in getDollars(): rate = 0.0 country = amount = 0.0
Country = Mexican Peso

It did not change anything the result was the same.

Do the rate and country variables now have valid values? If not, where in your code do you set the values? Add a println following EVERY place that you set their values to see where your code is changing good values to empty values.

What does the code do now? Please show enough of the output to show the problem and explain what is wrong with the output and show what the output should be.

Do the rate and country variables now have valid values? If not, where in your code do you set the values? Add a println following EVERY place that you set their values to see where your code is changing good values to empty values.

What does the code do now? Please show enough of the output to show the problem and explain what is wrong with the output and show what the output should be.

rate and country variables have valid values in the menu() method and empty values in the getDollars() method, the getDollars method is suppose to load the object array in a loop in lab9.
the summary report made from the object array is printed if user quits and enters yes to summary report prompt.
I changed the code so that menu choices print once only at the start of the program and I am not calling print Vertical() method so that the output won't be huge. These two changes don't effect the the code for loading and printing the object array.
This is the code for lab9 class and Foreign class:
import java.util.Scanner;

public class lab9
    {
        public static void main(String[] args)
        {
            
				final int Max = 10;
				int choice;
				
            String s;     
            char c; //choice for summary report
            int i = 0;
				Foreign foreignObject = new Foreign();                
				Foreign[] thelist = new Foreign[Max];//array of 10 reference variables of type "Foreign"  (null) 
				Scanner Keyboard =new Scanner(System.in);               
            Foreign.title();  
				
				do
            	{
                              
										 foreignObject.menu();
					  					
										choice=foreignObject.number;//gets choice number entered for choice
						  					 
					 			if(i < thelist.length)
					 						
									{
										 thelist[i] = new Foreign();//gives actual reference to memory large enough for a object of Foreign class
																				 
										 thelist[i]. getDollars();//can't get method or to toString to populate thelist object array
										 
										 i++;
										
										 //foreignObject.vertical();  I'm not calling this method and not printing 
										     //the menu choices onevery conversion run right now so the output will
											  // not be huge
					 					  										  
								    }
            
            }while (choice != 0 && i <= Max );//repeat until user enters "0" to quit
				
				System.out.print("\t\t\nWould you like to display a summary report? (y/n): ");
      		
				s = Keyboard.nextLine();
		 
     			c = s.charAt(0);
            
				 switch (c)
               {
               case 'y':
               case 'Y':
                 System.out.println("\nItem\t\tConversion\t\tDollars\t\tAmount");
						int cnt =foreignObject.count;
                 for (int index = 0 ; index < cnt ; index++)
					    { 
					      										 
					      System.out.print(thelist[index] + "\t");
                            
                   }
             }
             
            foreignObject.counter();
        }
    }

//=======================================
//=======================================
import java.util.Scanner;
import java.text.*;
 
 public class Foreign
    {
      public  int number;//number entered for choice
    	public  int n;
	 	public  int count = 0;//count of the number conversions made
		public  double dollars, amount;
		public  double rate;
	   public  String country ;
		public  String[] cName= {"","Canadian Dollars","Mexican Peso","Japanese Yen","Euros"};
    	public  double[] rates= {0,1.03,10.55,117.57,.8407};//0 and "" so index "i" matches number 1 choice
	   DecimalFormat rF = new DecimalFormat("##00.##");	
	   DecimalFormat money = new DecimalFormat("###,###,#00.##");
		static Scanner read=new Scanner(System.in);
     
    public Foreign()// constructor to initialize numerics to 0 and country to "" null

    {
    
	    country = "  ";
		 number=0;
		 rate = 0.0;
		 amount = 0.0 ;
		 dollars = 0.0;  

	      }
    public static void title()// a static method to display title
      {  
				System.out.println("\t\tForeign Exchange\n\n");
				System.out.println("\t\t1. U.S. to Canadian Dollars");
	     		System.out.println("\t\t2. U.S. to Mexican Pesos"); 
	     		System.out.println("\t\t3. U.S. to Japanese Yen"); 
	     		System.out.println("\t\t4. U.S. to European Euros"); 
	     		System.out.println("\t\t0. Quit\n\n"); 

		}
     
        public  void menu()
        {
        		System.out.println("\t\tEnter your choice: "); 
				do
					{ 
						n = read.nextInt();//to make sure user enters a valid menu choice 0-4
						if (n > 4 || n < 0)
						System.out.println("\t\tPlease enter 1 through 4 or 0 to quit:\n");
					}while (n > 4 || n < 0);
											
				
				number = n	;
       		rate=rates[number];//note rate and country both "work" in  menu() method but not in the getDollars()method

System.out.println("This is in menu() rate = "+rate+" number =  "+number );
		 
		  }  
		 
		  public void getDollars()//the method used to load the object array named thelist in lab9
			
			{
				 				
				   System.out.print("\t\tPlease enter amount in U.S. dollars:\n");
				  	dollars = read.nextDouble();
					country = cName [number];
					amount=dollars*rate;
					count++;

System.out.println("this is in getDollars()rate = "+rate+"  country = "+country+"  amount = " +amount+ "  dollars = "+dollars+" number = "+number);

			}
		  
		  
		  
	//public String addData() if someone has a better way to load the array that would be great. I am just following the prof's example code
    
	 public void vertical()//ignore this for now it will work when the above code works 
    			{
System.out.println("this is in vertical()rate = "+rate+"  country = "+country+"  amount = " +amount+ "dollars = "+dollars);
    			System.out.println("\t\tCountry = " + country );
				System.out.println("\t\tRate = " + rF.format(rate) );
				System.out.println("\t\tDollars US = " + money.format(dollars) );
				System.out.println("\t\t Foreign curency amount = " + money.format(amount) );
    }
   public String toString()   //a toString()method to display the data horizontally via a string returned to lab9
										//This method is not being called by lab9
			{
		 	 String line;// This method is not being called by lab9 I tried to load this to the object array but it would only take a Foreign type not a string	
			 line = "\n\n" + country +  "\t\t " + money.format(dollars) + "\t\t " + money.format(amount)+"\n\n";
			 return line;
			 }
    public  void counter()
    		{
			System.out.println("\nThe total number conversions made is " + count);
			}
}

========================================
========================================
This is the output:
Foreign Exchange


1. U.S. to Canadian Dollars
2. U.S. to Mexican Pesos
3. U.S. to Japanese Yen
4. U.S. to European Euros
0. Quit


Enter your choice:
4
This is in menu() rate = 0.8407 number = 4
Please enter amount in U.S. dollars:
6
this is in getDollars()rate = 0.0 country = amount = 0.0 dollars = 6.0 number = 0
Enter your choice:
3
This is in menu() rate = 117.57 number = 3
Please enter amount in U.S. dollars:
3
this is in getDollars()rate = 0.0 country = amount = 0.0 dollars = 3.0 number = 0
Enter your choice:
0
This is in menu() rate = 0.0 number = 0
Please enter amount in U.S. dollars:
0
this is in getDollars()rate = 0.0 country = amount = 0.0 dollars = 0.0 number = 0

Would you like to display a summary report? (y/n): y

Item Conversion Dollars Amount

The total number conversions made is 0

----jGRASP wedge2: exit code for process is 0.
----jGRASP: operation complete.

=============================================
===============================================
The output should be
If they select ‘Y’ then, using the array of objects, display the following report:

Item Conversion Dollars Amount
1 Japanese Yen 100.00 32,000.00
2 Mexican Peso 400.00 56,000.00
3 Canadian Dollar 100.00 156.00
etc.

Number of Conversions = 3

(the numbers above are only used for example, and do not represent real values)

Can you explain what is wrong with the program now? You post its output without any explanations of where the output is wrong. The more you show us what the problem is, the better will be the results.

If the problem is with the rate variable, You need to: Add a println following EVERY place that you set the values of rate and country to see where your code is changing good values to empty values.

Also you need to consider what object you are using to do what job with.
If you add an id String to the Constructor for the Foreign class: Foreign(String id), save it in a class variable and add it to all your printouts: println(id + ...) so you can tell which Foreign object is executing that will help you see what is happening in your code.

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.