简体   繁体   中英

Need help splitting input from a String into int

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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