我正在尝试制作手机资费计算器。但是我得到了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);
}
}
答案 0 :(得分:3)
您在此行中传递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
答案 1 :(得分:0)
您正在将null
传递给calculator()
方法并尝试在该方法中迭代它。
c.calculator(null); // passing null
....
public void calculator(List<Integer> tariff) { // tariff is null as you passed null from main method
...
for (Integer s : tariff) { // Trying to iterator over null, hence, NPE
whattariff = tariff.get(0);
mins = tariff.get(1);
texts = tariff.get(2);
}
您可能需要向calculate方法发送一个Integers列表。像这样的东西
// In main method
List<Integer> tariff = new ArrayList<>(); // new integer list for example
tariff.add(1); // add 1
tariff.add(2); // add 2
c.calculator(tariff); // pass the list to calculate method