gpt4 book ai didi

java - 电话资费计算器

转载 作者:行者123 更新时间:2023-12-01 23:23:27 25 4
gpt4 key购买 nike

我正在尝试制作一个电话资费计算器。但是我遇到了nullpointerexceptions。无法弄清楚他们从哪里来。帮助表示赞赏!

注意我确实有另一个类接受用户输入到列表中。但这正如预期的那样工作

  import java.util.ArrayList;
import java.util.List;

public class TariffCalc {

public void calculator(List<Integer> tariff){

int whattariff = 0;
int mins = 0;
int texts = 0;
int surchargeMin = 0;
int surchargeText = 0;
int totalsurcharge= 0;

for( Integer s: tariff ){
whattariff = tariff.get(0);
mins = tariff.get(1);
texts = tariff.get(2);
}

if ( whattariff == 1 && mins <= 200 && texts <= 150 ){
System.out.println("Tariff 1: Within Allowance: £20 per month: Mins used: " + mins + " Texts used: " + texts );
}
else if( whattariff == 1 && mins > 200 ){
surchargeMin = mins - 200;
surchargeMin = (int) (surchargeMin * 0.1);
}

if ( whattariff == 1 && texts > 150 ){
surchargeText = texts - 150;
surchargeText = (int) (surchargeText * 0.05);
}



if ( whattariff == 2 && mins <= 400 && texts <= 350 ){
System.out.println("Tariff 2: Within Allowance: £35 per month");
}
else if ( whattariff == 2 && mins > 400 ){
surchargeMin = mins - 400;
surchargeMin = (int) (surchargeMin * 0.1);
}

if ( whattariff == 2 && texts > 350 ){
surchargeText = texts - 350;
surchargeText = (int) (surchargeText * 0.05);
}

totalsurcharge = surchargeMin + surchargeText;

if( whattariff == 1)
System.out.println("Tariff 1: Allowance 200mins + 150 text. Used: " + mins + " + " + texts + ": Total Cost is £" + (20 + totalsurcharge) );
else if (whattariff == 2){
System.out.println("Tariff 2: Allowance 400mins + 350 text. Used: " + mins + " + " + texts + ": Total Cost is £" + (35 + totalsurcharge) );
}

}
public static void main(String[] args) {


TariffCalc c = new TariffCalc();
c.calculator(null);

}

}

最佳答案

您在此行中传递一个 null 对象:

c.calculator(null);

并且您尝试在这一行中进行迭代

for( Integer s: tariff )

这会让你的代码抛出异常。

你应该这样做:

List<Integer> tariffs = new ArrayList<Integer>();
tariffs.add(1);
tariffs.add(2);
tariffs.add(3);
c.calculator(tariffs);

这给了我输出:

Tariff 1: Within Allowance: £20 per month: Mins used: 2 Texts used: 3
Tariff 1: Allowance 200mins + 150 text. Used: 2 + 3: Total Cost is £20

关于java - 电话资费计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20349630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com