简体   繁体   English

为什么我得到 ArrayIndexOutOfBoundsException?

[英]why I am getting ArrayIndexOutOfBoundsException?

Hi I am unable to know what I am doing wrong.嗨,我不知道我做错了什么。 I have a string which is pass as an argument to a my class.我有一个字符串作为参数传递给我的 class。 I have to split that string and assign the respective values to the member variable but it is not working properly.我必须拆分该字符串并将相应的值分配给成员变量,但它无法正常工作。

Here is my class.这是我的 class。

    package virtusa;

public class pratice {
    
    String getName;
    Double getPrice;
    int getQuantity;
    String temp[]  = null;
    public pratice()
    {
        
    }
    public pratice(String rawInput)
    {
        temp = rawInput.split("$$##",2);
        getName = temp[0];
        getPrice = Double.parseDouble(temp[1]);
        getQuantity =Integer.parseInt( temp[2]);
    }
    public String getGetName() {
        return getName;
    }
    
    public Double getGetPrice() {
        return getPrice;
    }
    
    public int getGetQuantity() {
        return getQuantity;
    }


}

here is my main class这是我的主要 class

   package virtusa;

import java.util.Scanner;

public class demo {

    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        String stub = in.nextLine();
        
        pratice temp  = new pratice(stub);
        System.out.println(temp.getName);
        System.out.println(temp.getQuantity);
        System.out.println(temp.getPrice);
        

    }

}

My Input = apple$$##12.5$$##9我的输入 = 苹果$$##12.5$$##9

error i am having -我遇到的错误 -

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at virtusa.pratice.<init>(pratice.java:17)
    at virtusa.demo.main(demo.java:12)

String::split take regex as a parameter, so the $ has special meaning. String::split 以正则表达式为参数,因此$具有特殊含义。 You will need to escape it with a \你需要用\来逃避它

One of problems in your code in not escaping special characters as some comments are mentioning.正如一些评论所提到的,您的代码中的问题之一不是 escaping 特殊字符。 In my opinion clearest solution is to use Patter quote在我看来,最清晰的解决方案是使用 Patter 报价

rawInput.split(Pattern.quote("$$##"), 3);

Other problem is that you clearly need to get there elements since you are trying to get temp[0], temp[1] and temp[2]另一个问题是您显然需要获取元素,因为您正在尝试获取 temp[0]、temp[1] 和 temp[2]

So the final code should look something like this所以最终的代码应该是这样的

String getName;
Double getPrice;
int getQuantity;
String temp[] = null;

public Practice() {

}

public Practice(final String rawInput) {
    temp = rawInput.split(Pattern.quote("$$##"), 3);
    getName = temp[0];
    getPrice = Double.parseDouble(temp[1]);
    getQuantity = Integer.parseInt(temp[2]);
}

public String getGetName() {
    return getName;
}

public Double getGetPrice() {
    return getPrice;
}

public int getGetQuantity() {
    return getQuantity;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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