This is what the error says:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at FracCalc.produceAnswer(FracCalc.java:34)
at FracCalc.main(FracCalc.java:16)
And Here is my existing code:
import java.util.*;
public class FracCalc {
public static void main(String[] args)
{
// TODO: Read the input from the user and call produceAnswer with an equation
Scanner input = new Scanner(System.in);
System.out.println("Do you want to calculate something? If no, type in 'quit'. If yes, simply type in 'yes'. ");
String Continue = input.next();
if(Continue.equals("quit")){
System.out.println("Have a nice day! ");
}else if(Continue.equals("yes")){
System.out.println("Please input a fraction, there must be exactly one space between the operator and the operand. ");
String readInput = input.nextLine();
System.out.println(produceAnswer(readInput));
}
}
// ** IMPORTANT ** DO NOT DELETE THIS FUNCTION. This function will be used to test your code
// This function takes a String 'input' and produces the result
//
// input is a fraction string that needs to be evaluated. For your program, this will be the user input.
// e.g. input ==> "1/2 + 3/4"
//
// The function should return the result of the fraction after it has been calculated
// e.g. return ==> "1_1/4"
public static String produceAnswer(String input)
{
// TODO: Implement this function to produce the solution to the input
int space = input.indexOf(" ");
int nextspace = space + 2;
String operand = input.substring(0, space + 1);
String operator = input.substring(space + 1, nextspace);
String operand2 = input.substring(nextspace + 1, input.length());
return operand2;
}
// TODO: Fill in the space below with any helper methods that you think you will need
}
I'm trying to segregate fraction operators by determining the indexes of spaces and then going from there. Unfortunately i keep getting this error. Can someone please help! Thank You!