0

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.

  • 1 frequent flyer mile is earned for each mile traveled in coach.
  • 2 frequent flyer miles are earned for each mile traveled in first class.
  • 0 frequent flyer miles are earned on a discounted flight.

For example, given the data in input.txt below, your method must return 15600 (2*5000 + 1500 + 100 + 2*2000).

Input.txt:

firstclass 5000 coach 1500 coach
100 firstclass 2000 discount 300

My code gives me a problem with the parseint method. 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();
    }

}

}
5
  • 2
    "My code gives me a problem with the parseint method" - what problem, and with what input? Commented Mar 11, 2014 at 16:16
  • What is the error you see? Commented Mar 11, 2014 at 16:17
  • I re-formatted your input.txt file contents to be more readable but I wasn't sure if each pair of data (flight type & miles traveled) should be on a new line or not. Please update accordingly. Commented Mar 11, 2014 at 16:29
  • they should be on the next line, and thats the trick here ! Commented Mar 11, 2014 at 16:46
  • 1
    To be specific, the error is in the IsaInteger class where it throws a NumberFormatException when it accepts the "firstclass" string of the second line. I dont know why does the program stop running when I have a catch statement in the program ? Commented Mar 11, 2014 at 16:47

2 Answers 2

1

This is the stacktrace that I get when running your code:

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). The exception occurs when Integer.parseInt() tries to parse the string firstclass as an integer, which of course fails:

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

I rewrote your code in LA5ex2.java with two ArrayLists (to keep track of the various flier classes and the various mileages) using your IsaInteger method: 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;
    }
}

This code gives me the desired output: Frequent-flier miles the person earns: 15600

Sign up to request clarification or add additional context in comments.

1 Comment

@user3367892 If my answer solves your problem, I'd be happy if you mark it as "accepted answer" and/or vote it up :-)
0

I'm assuming the problem is in IsaInteger (which should be stylized as isAnInteger). In that case, add a line that prints out the value of s before the try/catch and tell me what you get.

Also, why are you using tokens when you could use a BufferedReader and its nextLine() method?

8 Comments

The program doesn't run even after adding this because there still is a problem with this function.
however I found out that its the string "firstclass" of the second line where it stops working
Can you paste the error message and the line on which it is occurring?
@user3367892 "problem" could be really many things (does not compile, does not return the expected value, throws an exception at runtime, etc.). You need to be more specific.
Exception in thread "main" java.lang.NumberFormatException: For input string: "firstclass" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at LA5ex2.main(LA5ex2.java:35)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.