簡體   English   中英

硬幣:無效的方法聲明,需要返回類型

[英]Coins : Invalid Method Declaration, return type required

我上周剛開始計算機科學,我們得到了一個名為Coins的工作表,在其中我必須找出一組硬幣中有多少個四分之一,一角硬幣,五分之一硬幣和幾分錢。 我遇到了很多麻煩,並且遇到了這個錯誤。 這是我的代碼

package Coins;


public class Coins
{
    private int change;

    // two contructors
    Change()    //default constructor
    {
        change = 94;
    }

    Change( int c )
    {
        change = c;
    }

    // accessor method - change
    public int getChange()
    {
            return Change;
    }



    // mutator method - change
    public void setChange( int anotherChange)
    {
        change = anotherChange;
    }

    public void askUserForChange()
    {
        Scanner keyIn;
        keyIn = new Scanner(System.in);

        System.out.print("Please enter the amount of change: ");
        String input = keyIn.nextLine();

        int nChange = Integer.parseInt (input);

        setChange(nChange);
        // change = nChange

        printChangex();
    }

    // action method - take accessor figure out coins -> output
    // calculating the coins needed for the change
    public void printChangeRange(int start, int end)
    {
        for(int c = start; c <= end; c++
        {
            setChange(c);
            printChangex();
        }

    }
    public void printChangex()
    {

    int c = change;
    int quarter = c / 25;
    System.out.println("quarter = " + quarter);
    int a = c%25;
    int dime = a / 10;
    System.out.println("dime = " + dime);
    int b = a%10;
    int nickel = b / 5;
    System.out.println("nickel = " + nickel);
    int c = b%5;
    int penny = c / 1;
    System.out.println("penny = " + penny);

    }


    // instance variables - replace the example below with your own
    private int x;

    public Coins()
    {
        // initialise instance variables
        x = 0;
    }

    public int sampleMethod(int y)
    {
        // put your code here
        return x + y;
    }
}

您有一個名為Coins的類,並且正在嘗試為其提供一個名為Change的構造函數。 類和構造函數必須具有相同的名稱。 選一個。

為了詳細說明標題中的錯誤,我假設“無效的方法聲明,需要返回類型”是指帶有Change() //default constructor 由於這是在名為Coins的類中,因此它不是注釋所聲稱的構造函數。 Java編譯器認為這是一種方法。 所有方法都必須具有返回類型,因此編譯器會抱怨。

實際的構造函數位於代碼的底部。 按照慣例,將構造函數放在首位,所以我建議您將這些以名字命名的構造函數放在Coins類的開頭。 您可能只需要完全刪除Change()構造函數。

另外,作為在此處提問的提示,發布所收到的完整錯誤消息也至關重要。 我的答案是基於一些有根據的猜測,當然不能解決代碼中的所有問題。 在繼續嘗試修復程序時,請隨時提出更多問題。

這個

// two contructors
Change()    //default constructor
{
    change = 94;
}

Change( int c )
{
    change = c;
}

不尋常。 您甚至在文件底部都有一個Coins類的構造函數,因此您想使用它。 請記住,所有Java類都具有與該類本身相同的名稱的構造函數-即使它是默認構造函數。

它在實例化時具有94的神奇價值,這更是不尋常了……但實際上,要選擇一個類名並堅持下去。

這個

// accessor method - change
    public int getChange()
    {
            return Change;
    }

...也很奇怪 您可能想返回成員變量change ,因此將其更改為小寫C。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM