创建构造函数

时间:2013-09-04 01:58:22

标签: methods constructor

我有一些我需要帮助的代码。我是一名AP CS学生(并且是介绍性的)所以请不要评判我。

// name:  
    //
    // program:  CoinsTester
    //
    // purpose: 

    public class CoinsTester {



         public static void main(String[] args) {
     //create a new Coins object named money and pass it the amount of cents as a parameter
  //***** STUDENTS NEED TO COMPLETE ******
      Coins(); 
      Coins money = new Coins(); 

        // call the correct method in the Coins class to find your answer
  //***** STUDENTS NEED TO COMPLETE ******
        money.calculate(); 


    }

}



// name:  
//
// program:  CoinsTester
//
// purpose: This class accepts a certain number of monetary change.
//         The output is a list of the number of quarters, dimes, nickels,
//    and pennies that will make that amount of change with the least
//    number of coins possible.  This is a skeleton that will be finished 
//       by the students

    public class Coins {

 //private variable to store the only attribute of a "Coins" object - how many cents the 
 //    user wants to find change for. 
 private int myChange;

 //constructor that accepts an initial value for the private data member
 public Coins(int change) {
  myChange = change;
 } 

     // the method calculate will 
     // 1. use modular and regular division to determine the quantity of each type of coin
     // 2. prints the quantity of the coins needed to make the entered amount 
      public void calculate(){
      int quarters=25, dimes=10, nickels=5, pennies=1;
      int temp1, temp2, temp3, temp4; 
      int remainquar1, remaindime2, remainnick3, remainpenn4; 

        //variable declarations to hold the values needed for different coin types
        // make sure you use descriptive identifiers!
       //***** STUDENTS NEED TO COMPLETE ******

       // calculations for the various coin types
       //***** STUDENTS NEED TO COMPLETE ******


      // output statements, formatted as shown on specs  
       //***** STUDENTS NEED TO COMPLETE ******

      }   

     }

所以这就是事情,我为我的格式不正确的代码道歉。因此,当我运行它时,它表示Coins money = new Coins()无法找到代码的构造函数。我需要帮助来创建一个合适的对象。这里的事情是我必须为“CoinsTester”创建一个对象,然后它告诉我没有链接到该对象的构造函数。我现在真的找不到解决方案。有人可以给我一些关于如何为CoinsTester类创建构造函数的技巧吗?

2 个答案:

答案 0 :(得分:0)

添加一个名为CoinsTester的“方法”(如果你需要CoinsTester类的构造函数,那么从你的Q中不清楚你需要什么构造函数)。如果要使用添加的显式构造函数,请确保参数对应于调用序列。

答案 1 :(得分:0)

您有两行需要审核:

Coins(); 

这将调用名为Coins的方法,而不是构造函数。我建议你删除它,因为你很可能不会使用/需要它。

Coins money = new Coins(); 

没有与之链接的构造函数的原因是你已经拥有了Coins的构造函数:

public Coins(int change) {
    myChange = change;
} 

创建此构造函数时,删除了默认构造函数 new Coins(); 。如果您希望能够使用没有参数的Coins构造函数,则可以再次声明它。这是一个例子:

public Coins() {
    myChange = 0;
}