第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何修復(fù)字符串索引超出范圍:-1

如何修復(fù)字符串索引超出范圍:-1

慕虎7371278 2023-12-13 15:14:43
我一直在研究一種生成密碼的方法,該方法會(huì)將每個(gè)“S”更改為$。請(qǐng)注意,我從另一個(gè)類中獲取該短語(yǔ),它始終大于 8 個(gè)字符    String key;    String store;    key = phrase.substring(0,1).toUpperCase();    phrase = key + phrase.substring(1,phrase.length());    System.out.println(phrase);    System.out.println(phrase.length());    for(int i = phrase.length(); i>0; i--) {        int sKey = phrase.indexOf('S');        store = "$" + phrase.substring(sKey+1,phrase.length());        phrase =phrase.substring(0,sKey)+store;        System.out.print(phrase);    }}但是之后我總是收到此錯(cuò)誤Exception in thread "main" Te$taaaajava.lang.StringIndexOutOfBoundsException: String index out of range: -1    at java.lang.String.substring(Unknown Source)    at edu.ilstu.Security.generatePassword(Security.java:15)    at edu.ilstu.SecurityApp.main(SecurityApp.java:57)
查看完整描述

3 回答

?
慕尼黑8549860

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊

索引超出范圍異常值 -1 表示未找到請(qǐng)求的符號(hào)(在本例中為 S)。



查看完整回答
反對(duì) 回復(fù) 2023-12-13
?
Helenr

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊

您接受phrase.indexOf('S')一個(gè)字符串而不檢查返回值。如果沒(méi)有匹配,該方法返回-1。然后,您使用該索引作為子字符串的上限,這會(huì)導(dǎo)致程序崩潰。

如果我正確理解你想要做什么,即使你得到了正確的算法,你也會(huì)想要一個(gè)不同的算法。沒(méi)有理由既在字符串中搜索所需字符的每次出現(xiàn),又編寫一個(gè)將長(zhǎng)度減 1 的循環(huán)。此外,如果可能,請(qǐng)避免復(fù)制長(zhǎng)數(shù)組和字符串。


查看完整回答
反對(duì) 回復(fù) 2023-12-13
?
繁星點(diǎn)點(diǎn)滴滴

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊

我不確定這是否是正確的方法。但是,我發(fā)現(xiàn)添加 if 語(yǔ)句實(shí)際上修復(fù)了此代碼,并在索引變?yōu)?-1 時(shí)停止 for 循環(huán)


    String key;

    String store;

    key = phrase.substring(0,1).toUpperCase();

    phrase = key + phrase.substring(1,phrase.length());

    for(int i = phrase.length(); i>0; i--) {

            int sKey = phrase.indexOf('S');

            if(sKey >= 0) {

            store = "$" + phrase.substring(sKey+1,phrase.length());

            phrase =phrase.substring(0,sKey)+store;

            }else {

                i=0;

            }

    }```


查看完整回答
反對(duì) 回復(fù) 2023-12-13
  • 3 回答
  • 0 關(guān)注
  • 203 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)