StringOutOfBoundsException 1 Java

时间:2017-11-24 00:20:20

标签: java

这就是错误所说的:

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)

这是我现有的代码:

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

}

我试图通过确定空间的索引然后从那里开始来分离分数运算符。不幸的是我一直收到这个错误。有人可以帮忙!谢谢!

1 个答案:

答案 0 :(得分:0)

您必须使用input.nextLine(),因为您想要阅读整行而不仅仅是字符。在您的主要方法中尝试这个:

    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.nextLine();
    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));
    }