我知道如何使用substring(),但是为什么不能正常工作,用户输入了一个等式
“ 5t +1”,在“ +”前后有一个空格。我希望tVariable在其之前保存整数,在此case 5中,常量应在此case 1中保存常量整数,但是出现了超出范围的错误。

import java.util.*;
import javax.swing.JOptionPane;

public class project3030  {
    public static void main(String[] args) {
        String L1x, tVariable, constant;
        L1x = JOptionPane.showInputDialog("This is the format (x=5t + 1)");

        int endIndex = L1x.indexOf("t");

        tVariable = L1x.substring(0, endIndex);

        int beginIndex = L1x.lastIndexOf(" ");
        int endIndex2 = L1x.indexOf("");

        constant = L1x.substring(beginIndex, endIndex2);

        System.out.println(tVariable + constant);
    }
}

最佳答案

您需要将其更改为更像

constant = L1x.substring(L1x.lastIndexOf(" ")).trim();


然后,在添加数字时,必须先解析它们,然后再添加它们。

int constantInt = Integer.parseInt(constant);


或者您可以使用以下解决方案:

String[] input = L1x.split(" ");

// remove the 't'
String tNum = input[0].substring(0, input[0].length() - 1);
int t = Integer.parseInt(tNum);
int constant = Integer.parseInt(input[2]);
String operator = input[1];

if (operator == "-")
    constant *= -1;

10-05 18:44