簡體   English   中英

如何修復 java 中我的文字問題求解器算法中的錯誤

[英]how do fix an error in my word problem solver algorithm in java

你好我正在嘗試創建一個解決單詞問題的算法

'' import java.util.Scanner;
   import java.io.BufferedReader;
   import java.io.FileNotFoundException;
   import java.io.FileReader;
   import java.io.IOException;
   import java.util.HashMap;
   import java.lang.*;
   public abstract class test {
    static Scanner s = new Scanner(System.in);

public static void check() throws IOException {
    String q = s.nextLine();

    
    boolean add[] = {q.contains("together"), q.contains("sum"), q.contains("more"),q.contains("plus"), q.contains("altogether")};
    
    if (add[0] == true || add[1] == true || add[3] == true || add[4] == true|| add[2] == true) {
        
        
        String[] split = {"and",",",".","more"};
        
        
    
        String[] parsedLine[] = {q.split(split[0]),q.split(split[1]),q.split(split[2]),q.split(split[3])};
        
         
        String[] num1 = {parsedLine[0][0],parsedLine[0][1],parsedLine[0][2],parsedLine[0][3]};
        
        String[] num2 = {parsedLine[1][0],parsedLine[1][1],parsedLine[1][2],parsedLine[1][3]};
        
        
        
        int numget1[] = {Integer.parseInt(num1[0].replaceAll("[\\D]", "")),Integer.parseInt(num1[1].replaceAll("[\\D]", "")),Integer.parseInt(num1[2].replaceAll("[\\D]", "")),Integer.parseInt(num1[3].replaceAll("[\\D]", ""))};
        int numget2[] = {Integer.parseInt(num2[0].replaceAll("[\\D]", "")),Integer.parseInt(num2[1].replaceAll("[\\D]", "")),Integer.parseInt(num2[2].replaceAll("[\\D]", "")),Integer.parseInt(num2[3].replaceAll("[\\D]", ""))};
        
        int res[] = {numget1[0] + numget2[0],numget1[1] + numget2[1],numget1[2] + numget2[2],numget1[3] + numget2[3]};
        
        
        
    }
}

public static void main(String[] args) throws IOException {

    
    String question = "if ben has 3 apples and bee has 4 apples how many apples do they have all together";

    check();


}}

我想要這個算法解決這個簡單的世界問題“如果本有 3 個蘋果,蜜蜂有 4 個蘋果,那么它們總共有多少個蘋果?”

基本上它檢查它是否添加它是否拆分它刪除字符串將其轉換為 int 然后添加 int 簡單但我收到此錯誤

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
    at mathproblemsolving.test.check(test.java:34)
    at mathproblemsolving.test.main(test.java:61)

String#split 將正則表達式作為參數。 這 ”。” 是“任何字符”的正則表達式,因此"Some.String".split(".")將返回一個空數組。

您需要轉義“.”,即"Some.String".split("\\n")將返回所需的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM