带有substring的Java数组 - 字符串索引超出范围异常

时间:2017-08-05 16:59:43

标签: java arrays loops for-loop substring

如何使用String index out of range处理异常?我接受了采访,并询问了下面的问题。

我有以下程序:

        String currentUserFirstName = "raj";
        String currentUserLastName = "ar";


        String strFoo[] = new String[]{
           (currentUserLastName.substring(0, 3)+"."+currentUserFirstName),
           (currentUserFirstName+"."+currentUserLastName.substring(0, 1))
        };


    for(int i=0; i<strFoo.length; i++){
        System.out.println(strFoo[i]);  
    }

我得到以下输出:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    at java.lang.String.substring(Unknown Source)

我想在下面得到以下输出:

Exception
raj.a

如果value的长度不足以进行子串,我想处理循环内的异常。

帮助将不胜感激!

EDITED 我尝试使用以下内容:

for(int i=0; i<strFoo.length; i++){
    try{            
       System.out.println(strFoo[i]);   
    }catch(Exception e){System.out.println("Exception");}
}

但它不起作用!

4 个答案:

答案 0 :(得分:1)

在使用 String.substring()方法之前,您需要考虑几个条件,以便在运行代码时不会遇到异常。首先当然是,如果任一字符串变量包含 Null Null String(“”);第二个是变量中包含的字符串长度,其中 .substring()方法将被处理,它是否具有足够的索引级别(长度)来表示要检索的字符数?

现在知道可能导致代码和/或输出错误的不同条件,您需要决定在出现这些特定条件时您想要做什么。

例如,假设 currentUserLastName 实际上包含一个空字符串(“”)。你有什么要忽略这个变量并且没有对它使用 .substring()方法,这样你最终会得到raj.或者你更愿意用空白部分填充哈希标记(#),以便您最终得到类似“raj.###的内容。也许最好只是告知用户需要姓氏而不是运行代码块。

同样适用于包含字符串长度的变量,该字符串长度不符合您要从其中包含的字符串中检索的字符数的索引要求。如果要从姓氏中检索3个字符,但姓氏只包含2个,那么您想要对第三个插槽做什么?忽略它并仅使用可用的两个字符:raj.ar或填充它并用第三个插槽填充哈希标记(#)或简单的空格:raj.ar#。您不能要求用户更改其姓氏,使其至少包含3个字符。

下面的示例代码演示了如何处理上述故障情况。当然,自然地假设变量 currentUserFirstName currentUserLastName 自然会通过硬编码以外的其他方式获取字符串但是为了这个例子,我们将简单地使用你提供了什么:

String currentUserFirstName = "raj";
String currentUserLastName = "ar";

// Make sure our variables contain data.
if (currentUserFirstName.isEmpty() || currentUserLastName.isEmpty()) { 
    // Display an error message to console if one does not.
    System.err.println("ERROR! Both the First and Last name must contain something!\n"
                     + "First Name: " + currentUserFirstName + "\n"
                     + "Last Name : " + currentUserLastName);
}
else {
    // Declare and initialize the strgFoo[] Array
    String strFoo[] = new String[2];
    // Does currentUserLastName contain at least 3 characters?
    if(currentUserLastName.length() >= 3) {
        // Yes it does...
        strFoo[0] = currentUserLastName.substring(0, 3)+"."+currentUserFirstName;
    }
    else {
        // No it doesn't so let's use the string length
        // inside currentUserLastName to determine our
        // required index for the .substring() method.
        strFoo[0] = currentUserLastName.substring(0, currentUserLastName.length()) + 
                    "." + currentUserFirstName;
    }
    // Fill in the second element for our Array
    strFoo[1] = currentUserFirstName+"." + currentUserLastName.substring(0, 1);

    // Iterate through the Array and
    // display its contents to Console.
    for(int i = 0; i < strFoo.length; i++){
        System.out.println(strFoo[i]);  
    }
}

答案 1 :(得分:0)

您应该将注意力从异常处理转移到更通用的代码设计。

通过异常控制算法通常是一种非常糟糕的做法。这就像过马路之前没有环顾四周,你只是跳到那里,如果你被车撞了,你现在开始考虑可能有一些交通的可能性。

相反,查询您使用的字符串的长度:

if (currentUserFirstName.length() >= 3) {
    currentUserLastName.substring(0, 3)...
} else {
    // something else, based on the fact that the string is not long enough
}

答案 2 :(得分:0)

一个重要的注意事项是错误是由于你试图获得0到3之间的字符而引起的。但是

0 - “r”,

1 - “a”,

2 - “j”,

3 - 这里没有任何字符,但您正在尝试访问它,因此会抛出异常。

你把你的try / catch放在错误的地方。

首先检查字符串的长度(更好)

要获取字符串的长度,可以访问其.length()方法,该方法不带参数。如果它大于3,则执行代码,否则不执行。

if(currentUserFirstName.length() > 3) {
    // your substring code
    // then your for loop
} else {
    // error handling
}

这可能更干净,因为消除异常并不总是一个好主意。

使用try / catch语句(更糟糕)

这是您在问题中尝试做的事情。只需在子字符串尝试周围移动一点。

try{
    String strFoo[] = new String[]{
       (currentUserLastName.substring(0, 3)+"."+currentUserFirstName),
       (currentUserFirstName+"."+currentUserLastName.substring(0, 1))
    };

    /* then either
         a) put your for-loop here
         b) mark a variable as true here, and check after the entire try/catch to see if you should run the loop
       neither is good. Best use the If/Else approach
    */
} catch(Exception e) { 
    System.out.println("Exception");
}

这样可行,但在这种情况下不需要使用try / catch,并且无论如何使用一个可能意味着如果你在同一段代码中有另一个错误,它将会默默地隐藏,你的代码会做出反应,好像你的子串超出了范围。

由于你最后的for循环依赖于所有成功的东西,你必须确保在继续之前没有任何失败。执行此操作的最佳方法是切换到if / else方法(并将for-loop放在“if”部分中)。如果你不想这样做,你可以把你的代码放在“try”部分(但如果你的for循环中有其他问题,你的代码会因为子字符串问题而假设它);或者将变量标记为truefalse,具体取决于代码是否进入catch阶段,然后将for循环置于if语句中,但这又是马虎。

在我看来,最好的方法是,正如我所提到的,使用if / else方法。使用try / catch来处理这些问题很少是干净的代码。

答案 3 :(得分:0)

StringIndexOutOfBoundsException不会从循环中抛出。 异常来自此处:currentUserLastName.substring(0,3)

它发生了,因为姓氏长度是2,你传递0到3,它应该只有0到2。 在以下情况下,subString方法抛出异常: - 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex。

因此在substring中我们可以将0传递给currentUserLastName.length()

相关问题