2017-08-05 76 views
0

給出的代碼引發StringIndexOutOfBoundException異常。有人請幫助我,我怎麼能解決這個例外....longestName在此拋出異常StringIndexOutOfBoundException。我應該如何解決它?

public static void longestName(Scanner console, int n) { 

    String name = ""; 
    String longest= ""; 
    boolean tie = false; 
    for(int i=1; i<=n; i++) { 
     System.out.print("Enter name #" + i + ":"); 
     name = console.next(); 
     if(name.length() == longest.length()) { 
      tie = true; 
     } 
     else if(name.length() > longest.length()) { 
      tie = false; 
     } 
    } 
    // now change name to all lower case, then change the first letter 
    longest = longest.toLowerCase(); 
    longest = Character.toUpperCase (longest.charAt(0)) + longest.substring(1); 

    System.out.println(longest + "'s name is longest"); 
    if(tie==true) { 
     System.out.println(" (There was a tie!) "); 
    } 
} 
+1

在您的代碼中'longest'總是空的... – assylias

+0

Exception是指什麼行? –

+0

longest = Character.toUpperCase(longest.charAt(0))+ longest.substring(1);這個你的異常行最長始終是空的,所以longest.charAt(0)會拋出異常 – Sreemat

回答

0
longest = Character.toUpperCase (longest.charAt(0)) + longest.substring(1); 

longest總是空"",所以在使用charAt(0)拋出indexOutOfBoundException因爲在longest

0

嘆息沒有字符數得有50個評論是愚蠢的。很多時候評論比答案要好,但我們在這裏大聲笑。他們是正確的,你永遠不會增加價值最長。但是你也有其他一些問題。

領帶是一個布爾值,所以你不需要== TRUE,只是如果你不這樣做,for循環右(並列){}代碼

下一步。我知道他們在小學時教會每個人都錯了。第一個數字爲0,你的for循環將總是以寫入的方式失去1次迭代。 for(int i = 0; i < = n; ++ n)所以,你有不止一件小事情在繼續。得到一些咖啡!總是有幫助。

String name = ""; 
String longest= ""; 
boolean tie = false; 
for(int i=0; i<=n; i++) { 
    System.out.print("Enter name #" + i + ":"); 
    name = console.next(); 
    longest = someweirdlongrandompersonsnamehere; 
    if(name.length() == longest.length()) { 

     tie = true; 
    } 
    else if(name.length() > longest.length()) { 
     tie = false; 

    } 
} 
// now change name to all lower case, then change the first letter 
longest = longest.toLowerCase(); 
longest = Character.toUpperCase (longest.charAt(0)) + longest.substring(1); 

System.out.println(longest + "'s name is longest"); 
if(tie) { 
    System.out.println(" (There was a tie!) "); 
} 
相關問題