0

The given code throwing StringIndexOutOfBoundException exception. Someone Please help me how can I solve this exception....

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! ) " );
    }
}
Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
Anonymous
  • 3
  • 1

2 Answers2

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

longest is always empty"", so while using charAt(0) throws indexOutOfBoundException because there is no Chars in longest

Ryan
  • 24
  • 4
0

Sigh have to have 50 to do a comment is silly. Many times comments are better than an answer but here we go lol. They are correct, you never add a value to longest. However you have some other issues too.

tie is a Boolean, so you don't need to == true, just if(tie){code}

Next you aren't doing that for loop right. I know they teach everyone wrong in grade school. THE FIRST NUMBER IS 0 your for loop will always lose 1 itteration the way it is written. for(int i=0; i <= n; ++n) So, you have more than one little thing going on. Get some coffee! Always helps.

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! ) " );
}
Xype
  • 68
  • 11