java - 电话资费计算器

标签 java arraylist

我正在尝试制作一个电话资费计算器。但是我遇到了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/

相关文章:

JAVA生成一行 "* "的最佳方式

Java 类型 T 的泛型集合,添加会引发编译错误,但检索和添加不会抛出编译错误

java - 如何使用正弦/余弦波返回振荡数

java - 如何一次将一个字符串添加到 HashMap<Integer, List<String>> 中?

java - 获取 ArrayList 的值时出现意外的 IndexOutOfBoundException

java - gradle从所有jar中排除外部资源文件夹

java.lang.NullPointerException

java - HashMap(键 : String, 值 : ArrayList) returns an Object instead of ArrayList?

java - 我不想输入列表的大小,但我也想在列表中动态添加数字

Java Android :Add array 15times in one second How?