給出的代碼引發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!) ");
}
}
在您的代碼中'longest'總是空的... – assylias
Exception是指什麼行? –
longest = Character.toUpperCase(longest.charAt(0))+ longest.substring(1);這個你的異常行最長始終是空的,所以longest.charAt(0)會拋出異常 – Sreemat