首页 > 解决方案 > 在数组函数中相乘

问题描述

$ 这是完整的代码

import javax.swing.JOptionPane;

public class Testing {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // Asks how many bills you want to calculate
    int numBills = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Bills you want to calculate"));

    // Declares the variables and elements in array
    double[] tkw = new double[numBills];
    double[] hours = new double[numBills];
    double[] ckwh = new double[numBills];
    double[] totalkwh = new double[numBills];
    double[] totalconsu = new double[numBills];
    double[] billtotal = new double[numBills];
    int i = 0;

    // Asks the values to calculate the bill
    while (i < numBills) {
        tkw[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter the Total Kilowatts used: " + i));
        hours[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter Number of Hours a month: " + i));
        ckwh[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter Cost per Kilowatt hour (kWh): " + i));
        // the calculation of the bills
        totalkwh[i] = tkw[i] * hours[i] * 30;
        totalconsu[i] = totalkwh[i] / 1000;
        billtotal[i] = totalconsu[i] * ckwh[i];
        i = i + 1;
    }
    i = 0;
    while (i < numBills) {
        // Retrieve and display value at i (current element)
        System.out.println(i + " The Total cost of your Electricity Bill is $ " + billtotal);
        i = i + 1;
    }
}

}

如果我想运行 2 个账单,这是我使用的输入

账单 1 tkw = 100 , hours = 10 , ckwh = 5

账单 2 tkw = 200 , hours = 20 , ckwh = 7

账单 1 的输出应为“您的电费总成本为 150.0 美元”

账单 2 的输出应为“您的电费总成本为 840.0 美元”

当我运行 2 张钞票的代码时得到的输出是

" 0 你的电费总成本是 $ [D@5fcfe4b2

1 您的电费总成本为 $ [D@5fcfe4b2"

标签: javaarrays

解决方案


你可以这样做

double[] billtotal = new double[numBills];
int i = 0;

while (i < numBills) {
    tkw[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter the Total 
    Kilowatts used: " + i));
    hours[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter Number 
    of Hours a month: " + i));
    ckwh[i] = Double.parseDouble(JOptionPane.showInputDialog("Enter Cost per 
    Kilowatt hour (kWh): " + i));

    totalkwh[i] = tkw[i] * hours[i] * 30;
    totalconsu[i] = totalkwh[i] / 1000;
    billtotal[i] = totalconsu[i] * ckwh[i];
    i = i + 1;
}

i = 0;
while (i < numBills) {
    // Retrieve and display value at i (current element)
    System.out.println(i + " The Total cost of your Electricity Bill is $ " + billtotal[i]);
    i = i + 1;
}

推荐阅读