首页 > 解决方案 > 初学者 Java 项目:我的数组有什么问题?

问题描述

作为大学课程的一部分,我刚刚开始学习 Java,并且在第一个项目中遇到了问题。我刚刚开始创建一个基本上对硬币进行分类的项目。我正在尝试创建一个名为 printCoinList() 的方法,该方法打印硬币列表的内容,指示当前流通的面额(即“流通中的当前硬币面额:200,100,50,20,10),以美分表示。

到目前为止,我已经声明了我的实例字段,创建了一个参数并尝试创建此方法。我唯一的问题是,当我尝试在 main() 方法中对其进行测试时,使用数组作为 coinList 参数似乎有问题。这是我到目前为止所拥有的:

public class CoinSorter {

    //Instance Fields
    String currency;
    int minCoinIn;
    int maxCoinIn;
    int[] coinList;
    
    //constructor
    public CoinSorter(String Currency, int minValueToExchange, int maxValueToExchange, int[] initialCoinList) {
        currency=Currency;
        minCoinIn=minValueToExchange;
        maxCoinIn = maxValueToExchange;
        coinList= initialCoinList;
        
    }
    
                public void printCoinList() {
        System.out.println("The current coin denominations are in circulation"
                + coinList);
    }
    
    
    public static void main(String[] args) {
        //An example
        
        CoinSorter exampleOne = new CoinSorter("pounds", 0, 10000, {10,20,50,100,200});

唯一的问题似乎在 exampleOne 中,因为当我将其取出时,其余代码似乎运行良好。错误信息是:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The constructor CoinSorter(String, int, int, int, int, int, int, int) is undefined
    Syntax error on token "{", delete this token
    Syntax error on token "}", delete this token

那么有谁知道我做错了什么?

标签: javaarrayssortingmethods

解决方案


可以使用以下方式之一声明/初始化 java 中的数组。

int[] myIntArray = {10,20,50,100,200};
int[] myIntArray = new int[]{10,20,50,100,200};

代替 CoinSorter exampleOne = new CoinSorter("pounds", 0, 10000, {10,20,50,100,200});

  CoinSorter exampleOne = new CoinSorter("pounds", 0, 10000, myIntArray );

或者

   CoinSorter exampleOne = new CoinSorter("pounds", 0, 10000, new int[]{10,20,50,100,200});

推荐阅读