0

Yesterday, I attempted to do this one way...today I am trying another and I am still stuck. I have to find a way of doing this using integer division and mod. Here is my code followed by the error messages.

public int evaluateFraction(int w, int n, int d)
    throws NumberFormatException
{
    whole = w;
    numerator = n;
    denominator = d;
    return portion2;
}

Tester

    input = JOptionPane.showInputDialog("Enter");

    portion2 = Integer.parseInt(input);`

error messages:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1 1/8"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at ClientCode.main(ClientCode.java:43)

Java Result: 1

What on earth am I doing wrong now?

Java Newb
  • 101
  • 1
  • 1
  • 7
  • 1
    Are you actually calling `evaluateFraction`? You need to rethink the approach a little as you should realize that you're accepting a string and returning a double from the fraction. – nanofarad Oct 08 '13 at 17:05
  • What is input, portion2? Please give as a sscce. – EProgrammerNotFound Oct 08 '13 at 17:08
  • Just throwing in unrelated and unused code will just make a mess, not help. You need to actually understand what you are doing. – Peter Lawrey Oct 08 '13 at 17:09
  • I have to put together the value in dollars and in eighths. I used portion1 for dollars and portion2 for eighths. – Java Newb Oct 08 '13 at 17:11
  • I understand that I need to "understand", it's quite clear that I do not. Hence, the sole reason for which I am seeking help. – Java Newb Oct 08 '13 at 17:12

3 Answers3

1

Integer.parseInt is able to parse only valid integer strings. If the input string contains anything other than digits then it will throw NumberFormatException.

You are trying to parse an expression 1 1/8, which is not a valid integer string.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • And to add, `evaluateFraction` is really not being used/usable here. – nanofarad Oct 08 '13 at 17:05
  • How should I go about this then? I've tried everything I know and nothing so far. – Java Newb Oct 08 '13 at 17:07
  • @AP you should better try to split your string using different arithemetic operators. You need to do this with all valid operators, get the operands and then work accordingly. – Juned Ahsan Oct 08 '13 at 17:09
  • I'd be lying if I said I had any idea how to go about doing this. Would you mind helping me out a bit more? – Java Newb Oct 08 '13 at 17:17
0

"1 1/8" is not a number. 1 and 8 are, whitespace and / are not. You need to parse such expression by hand.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
0

1 1/8 is not an integer, Integer.parseInt can perform well in the only one case, if data is valid.

Don't know, what result you expect but you either need some other method or parse it yourself.

ST3
  • 8,826
  • 3
  • 68
  • 92