Integer.parseint异常

时间:2014-03-11 16:15:01

标签: java

问题是: 编写一个程序来处理一个input.txt文件,该文件包含关于票据类型的数据,然后是里程数,并报告该人获得的常客里程数。

  • 教练每走一英里就可获得1飞行里程。
  • 头等舱每行程可获得2张飞行常客里程。
  • 通过折扣航班赢取0飞行常客里程。

例如,根据下面input.txt中的数据,您的方法必须返回15600(2 * 5000 + 1500 + 100 + 2 * 2000)。

INPUT.TXT:

firstclass 5000 coach 1500 coach
100 firstclass 2000 discount 300

我的代码给了我一个parseint方法的问题。任何帮助将不胜感激:)

//InInteger class
import java.lang.NumberFormatException;
public class IsInteger {

public static  boolean IsaInteger (String s)throws  NumberFormatException 
{
    try
    {
        Integer.parseInt(s);//converts the string into an integer
        return true;
    }
    catch (NumberFormatException e)
    {
        return false;
    }
}

}

//main class

import java.io.*;
import java.util.StringTokenizer;


public class LA5ex2 {

public static void main(String[] args) throws FileNotFoundException {


BufferedReader input= new BufferedReader (new InputStreamReader (new FileInputStream("C:/Users/user/workspace/LA5ex2/input.txt")));
    String str;
    int TotalMiles=0;
    try {
        int mileage,lines=0;
         String check,copy=null;
         String word=null;
         boolean isString=false;

        while ((str = input.readLine()) != null)
        {
            lines++;
            StringTokenizer token = new StringTokenizer(str);
            while (token.hasMoreTokens()) 
            {
                if ((lines>1) && (isString))
                {
                    //do nothing
                }
                else    
                {word= token.nextToken();
                copy=word;}
              if (token.hasMoreTokens())
                  mileage= Integer.parseInt(token.nextToken());
              else
              {
                  if (!(IsInteger.IsaInteger(word)))
                  {
                      copy=word;
                      isString=true;
                  }

                  break;
              }
            if (copy.equals("firstclass"))
                TotalMiles+= (2*mileage);
            else if (copy.equals("coach"))
                TotalMiles+= (1*mileage);
            else if (copy.equals("discount"))
            TotalMiles+= (0*mileage);
            }
        }


System.out.println("Frequent-flier miles the person earns: "+ TotalMiles);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

2 个答案:

答案 0 :(得分:1)

这是我在运行代码时得到的堆栈跟踪:

Exception in thread "main" java.lang.NumberFormatException: For input string: "firstclass"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:481)
    at java.lang.Integer.parseInt(Integer.java:514)
    at LA5ex2.main(LA5ex2.java:30)

我认为这是您在评论中提到的错误。但是,NumberFormatException类中的IsaInteger()方法中没有出现IsInteger(您尝试通过返回truefalse来抓住它),但在LA5ex2类中(您也尝试捕获它,但如果它崩溃,则只打印堆栈跟踪)。当Integer.parseInt()尝试将字符串firstclass解析为整数时会发生异常,这当然会失败:

if(token.hasMoreTokens()) mileage = Integer.parseInt(token.nextToken());

我使用您的LA5ex2.java方法在ArrayList中用两个IsaInteger重写了您的代码(以跟踪各种传单类和各种里程):     import java.io. *;     import java.util.ArrayList;     import java.util.StringTokenizer;

public class LA5ex2 {

    public static void main(String[] args) throws FileNotFoundException {

        BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
        String str = null;
        String token = null;
        int totalMiles = 0;
        int lines = 0;
        ArrayList<String> flierClasses = new ArrayList<String>();
        ArrayList<Integer> mileages = new ArrayList<Integer>();

        try {
            while((str = input.readLine()) != null) {
                lines++; // Why are we counting the lines, anyway?
                StringTokenizer tokenizer = new StringTokenizer(str);
                while(tokenizer.hasMoreTokens()) {
                    token = tokenizer.nextToken();

                    if(!(IsInteger.IsaInteger(token))) {
                        flierClasses.add(token); // if it's not an int, we assume it's a flier class
                    } else {
                        mileages.add(Integer.parseInt(token)); // if it's an int, it's a mileage
                    }
                }
            }
        } catch(NumberFormatException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        } catch(IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }

        // Add everything up
        for(int i = 0; i < flierClasses.size(); i++) {
            totalMiles += calculateFlierMiles(flierClasses.get(i), mileages.get(i));
        }

        System.out.println("Frequent-flier miles the person earns: " + totalMiles);
    }

    private static int calculateFlierMiles(final String flierClass, final int mileage) {
        if(flierClass.equals("firstclass")) return(2 * mileage);
        else if(flierClass.equals("coach")) return(1 * mileage);
        else if(flierClass.equals("discount")) return(0 * mileage);
        return 0;
    }
}

此代码为我提供了所需的输出:Frequent-flier miles the person earns: 15600

答案 1 :(得分:0)

我假设问题出在IsaInteger(应该将其设置为isAnInteger)。在这种情况下,添加一行在try / catch之前打印出s的值并告诉我你得到了什么。

此外,为什么在使用BufferedReader及其nextLine()方法时使用令牌?