简体   繁体   English

Integer.parseint异常

[英]Integer.parseint exceptions

The question was : Write a program that processes an input.txt file that contains data regarding ticket type followed by mileage covered and reports how many frequent-flier miles the person earns. 问题是:编写一个程序来处理input.txt文件,该文件包含有关机票类型的数据以及其后的行驶里程,并报告该人赚取了多少飞行常客里程。

  • 1 frequent flyer mile is earned for each mile traveled in coach. 乘坐教练每行驶1英里,即可赚取1英里飞行常客里程。
  • 2 frequent flyer miles are earned for each mile traveled in first class. 头等舱每飞行一英里可赚取2英里飞行常客里程。
  • 0 frequent flyer miles are earned on a discounted flight. 折扣航班可赚取0英里飞行常客里程。

For example, given the data in input.txt below, your method must return 15600 (2*5000 + 1500 + 100 + 2*2000). 例如,给定下面input.txt中的数据,您的方法必须返回15600(2 * 5000 + 1500 + 100 + 2 * 2000)。

Input.txt: INPUT.TXT:

firstclass 5000 coach 1500 coach
100 firstclass 2000 discount 300

My code gives me a problem with the parseint method. 我的代码给我parseint方法带来了问题。 Any help would be appreciated :) 任何帮助,将不胜感激 :)

//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();
    }

}

}

This is the stacktrace that I get when running your code: 这是我在运行代码时得到的stacktrace:

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)

I assume this is the error that you mention in your comment. 我认为这是您在评论中提到的错误。 However, the NumberFormatException does not occur in your IsaInteger() method in the IsInteger class (where you try-catch it by returning true or false ), but in the LA5ex2 class (where you also try-catch it, but if it crashes, only the stacktrace gets printed). 但是, NumberFormatException不会在IsInteger类的IsaInteger()方法中IsInteger (您可以通过返回truefalse尝试捕获它),而在LA5ex2类中(也可以尝试捕获它,但是如果崩溃,仅显示堆栈跟踪)。 The exception occurs when Integer.parseInt() tries to parse the string firstclass as an integer, which of course fails: Integer.parseInt()尝试将字符串firstclass解析为整数时,会发生异常,这当然会失败:

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

I rewrote your code in LA5ex2.java with two ArrayList s (to keep track of the various flier classes and the various mileages) using your IsaInteger method: import java.io.*; 我使用您的IsaInteger方法用两个ArrayList重写了LA5ex2.java的代码(以跟踪各种飞行器类和各种里程):import java.io. *; import java.util.ArrayList; 导入java.util.ArrayList; import java.util.StringTokenizer; 导入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;
    }
}

This code gives me the desired output: Frequent-flier miles the person earns: 15600 这段代码为我提供了所需的输出: Frequent-flier miles the person earns: 15600

I'm assuming the problem is in IsaInteger (which should be stylized as isAnInteger ). 我假设问题出在IsaInteger (应将其样式化为isAnInteger )。 In that case, add a line that prints out the value of s before the try/catch and tell me what you get. 在这种情况下,请在try / catch之前添加一行输出s值的行,并告诉我您得到了什么。

Also, why are you using tokens when you could use a BufferedReader and its nextLine() method? 另外,当可以使用BufferedReader及其nextLine()方法时,为什么还要使用标记?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM