3
public Fraction (String fractionString)
{
  StringTokenizer st = new StringTokenizer(fractionString, "/");
  numerator = Integer.parseInt(st.nextToken());
  denominator = Integer.parseInt(st.nextToken());
}

I have this so far. How do I change this to ignore parentheses in a fraction?

Example: (3/4) - how do I ignore these parentheses?

Looking at this would I be able to simply do StringTokenizer st = new StringTokenizer(fractionString, "/()"?

2 Answers2

2

One way to ignore symbols such as ()+-*/ is to use one of the overloaded constructors for StringTokenizer.

StringTokenizer st = new StringTokenizer(fractionString, "()", false);

The boolean for the third argument denotes whether or not the tokenizer will put the given delimeters, in this case parentheses, into tokens themselves (true), or skip over them while tokenizing the rest of the string (false).

Jodo1992
  • 745
  • 2
  • 10
  • 32
1

You can use .replace(char oldChar,char newChar)

public Fraction (String fractionString)
{   
    fractionString = fractionString.replace("(","");
    fractionString = fractionString.replace(")","");
    StringTokenizer st = new StringTokenizer(fractionString, "/");
    numerator = Integer.parseInt(st.nextToken());
    denominator = Integer.parseInt(st.nextToken());
}

Output from code:

(3/4)
numerator: 3    denominator: 4

Alternatively, you can use .split(String regex)as follows:

String[] split = fractionString.split("[()/]");
numerator = Integer.parseInt(split[0]);
denominator = Integer.parseInt(split[1]);
Chaos
  • 11,213
  • 14
  • 42
  • 69