java - 关于java和数组在方法中搜索并返回数据

标签 java arrays methods

这是我到目前为止所做的程序。我应该要求收银员输入价格,如果是宠物,则输入 y 或 n。然后应该有一个方法来计算有 5 件或更多商品时的折扣。除了折扣方法的返回数据之外,我的程序正在运行。

错误为 68:错误;无法从结果类型为 void 的方法返回值。

我很困惑为什么数据无效。如果我去掉returndiscount;语句,那么程序编译不会出错。

import javax.swing.JOptionPane;

public class Assignment4
{
    public static void main (String[] args) 
    {
        double[] prices = new double[1000];
        boolean[] isPet = new boolean[1000];
        double enterPrice = 0;
        int i = 0;
        String yesPet = "Y";
        int nItems = 0;
        do
        {
            String input = JOptionPane.showInputDialog("Enter the price for the item: ");
            enterPrice = Integer.parseInt (input);

            prices[i] = enterPrice;

            String petOrNo = JOptionPane.showInputDialog("Is this item a pet? Enter Y for pet and N for not pet.");

            if (petOrNo.equalsIgnoreCase(yesPet))
            {
                isPet[i] = true;
            }
            else
            {
                isPet[i] = false;
            }
            i = i+1;
            nItems = nItems + 1;
        } while (enterPrice != -1);
        //System.out.println(nItems);
    }

    public static void discount(double[] prices, boolean[] isPet, int nItems)
    {
        boolean found = false;
        double[] discount = new double[nItems];

        if (nItems > 6)
        {
            for (int i = 0; i < nItems; i++)
            {
                if (isPet[i] = true)
                {
                    found = true;
                    break;
                }
            }

            if (found = true)
            {
                for (int x = 0; x < nItems; x++)
                {
                    if (isPet[x] = false)
                    {
                        int n = 0;
                        prices[x] = discount[n];
                        n = n + 1;
                    }
                }
            }
        }
        return discount;
    }
}

最佳答案

discount 方法需要返回一个 double 数组。改变

public static void discount(double[] prices, boolean[] isPet, int nItems) {

public static double[] discount(double[] prices, boolean[] isPet, int nItems) {

没有为 discount 数组中的任何条目分配任何值,因此每个值都将为 0.0

关于java - 关于java和数组在方法中搜索并返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13215136/

相关文章:

java - 为通用数据库模型设计数据访问层

PHP:SQL 查询数组的最佳方法是什么? (如果你可以的话)

javascript - 一个对象如何从对象列表中分组并仅收集明确引用的特定值,每个值都通过其键?

c# - 这些默认参数的人造模拟之间是否存在显着的机械差异?

Python简单的POST方法

python - 如何确定实例方法对应的类?

java - Scala:直接或通过包装器访问 Java 原语?

java - ScheduledExecutorService 和取消行为

java - 在 Android Studio 中使用 Spinner 添加图像

java - 如何移动数组中的元素?