1

I have the user input a fraction problem in this format (4/8–3/12 or 3+2/3 or 12/16*4 or -2/3/64/96) and need to split up the two fractions into an array then I need to pull the numerator and denominator of both so I can simplify them in my other file and do whatever calculation it asks, so I need to use an array so i can call on the element that has the sign in it.

System.out.println("Enter Fraction:");
String answer = s.nextLine(); 


String[] numbers = answer.split(" ");
System.out.print(numbers);

Is there a way to split the array into int variables? I am lost. The solution might be simple but been at this project for 7 hours or so now.

3 Answers 3

1

You can split the input with a simple regular expression, like this:

Pattern p = Pattern.compile("\\d+|[+-/*]");
String inp = "2/3/64/96";
Matcher m = p.matcher(inp);
while (m.find()) {
    System.out.println(m.group());
}

The heart of this solution is a regular expression:

\\d+|[+-/*]

\\d+ means "one or more digit; [+-/*] means "any of the +, -, /, or *".

Here is a demo on ideone.

Note that your program would need to be really careful about deciding if a + or a - is a unary "change sign" or a binary operation: when the sign is at the beginning or just after another operator, it's unary; otherwise, it's binary.

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

Comments

0

Eric Lippert has the best advice I've seen when dealing with these problems.

Write the problem out in english/pseudo code then start changing the pseudo code to real code.

Get Answer from user
Break Answer up to the 2 fractions/numbers and the math operator
Take the 2 different fractions and convert them to a double, float, whatever you need
Apply the math operation to the 2 numbers from the above step
Output the answer

Now just start replacing each line with how you would do that. I feel confident that you can probably figure out each step, but sometimes we get lost when thinking of the problem as a whole. If you can't figure out an individual step, post the code you have tried and we can help with a specific problem.

2 Comments

I would rather not convert them to double or float as I am finding the lowest form the fraction could take of both fractions and the answer.
Hence why I added the section saying "whatever you need", the double/float was just a suggestion.
0

Your code so far just splits input into expressions. Your still need to split expressions into fractions.

When you already have String array of fractions you can split each element into 2 integers:

  1. Split it into sub-strings with split("/")

  2. Convert each sub-string to int with Integer.parseInt() method.

Comments

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.