簡體   English   中英

StringIndexOutOfBoundsException:

[英]StringIndexOutOfBoundsException:

我知道這個錯誤已經被問了很多。 我看過它們,但仍然不明白它如何適用於我的問題。 我正在嘗試編寫一個從字符串創建菱形圖案的程序。

public static String nameDiamond(String s) {
    int len = s.length();
    int i = 0;
    String out = "";
    while(i < len) { 
        out = out + s.substring(0, i + 1) + "\n";
        i++;
    }
    while(i > 0) { 
        int numSpaces = len - i + 1;
        for(int j = 0; j < numSpaces; j++)
            out = out + " ";
        out = out + s.substring(len - i + 1, i - 1) + "\n";
        i--;
    }
    return out;
}

現在我對substring的理解是,它的結構類似於s.substring(startIndex, endIndex)並且導致此錯誤的原因可能是結束索引小於開始但我不認為這是這里的問題。 我還看到錯誤的一些原因是某些東西不存在,但我再次認為這不是問題所在。 我錯過了什么?

當它用“Marty”測試時,它說-1和“Bill Nye”它說-2 空間會導致這種情況嗎?

我查看了許多其他版本的問題,但似乎相關的問題是:

StringIndexOutOfBoundsException:字符串索引超出范圍

StringIndexOutOfBoundsException:字符串索引超出范圍:-1

但我認為它們不適用。

作為參考,這是問題所在: https://www.codestepbystep.com/problem/view/java/strings/nameDiamond

這是一個您可以用作示例的示例。 它並不能完全滿足您的要求,但它會說明一件重要的事情。 對於固定寬度 fonts,每行必須是奇數個字符。 否則他們將無法正確排列。

如果n是偶數,則此特定版本將為nn+1打印相同的菱形。 它還受到空格字符串的限制。

public static void printDiamond(int len) {
    String str = "*";
    String space = "                              ";
    for (int i = 0; i < len/2 + 1; i++) {
        System.out.print(space.substring(0,len/2-i));
        System.out.println(str);
        str = str+"**";
    }
    str = str.substring(2);
    for(int i = 0; i < len/2; i++) {
        str = str.substring(2);
        System.out.print(space.substring(0,i+1));
        System.out.println(str);
    }
}

在調試程序時,使用無處不在的打印語句來打印不同的變量,例如索引和字符串長度。

暫無
暫無

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

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