longestName在此抛出异常StringIndexOutOfBoundException。我该怎么解决?

时间:2017-08-05 06:28:47

标签: java

给定的代码抛出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! ) " );
    }
}

2 个答案:

答案 0 :(得分:0)

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

longest始终为空"",因此在使用charAt(0)时会indexOutOfBoundException因为longest中没有字符

答案 1 :(得分:0)

叹息必须有50个评论是愚蠢的。很多时候评论比答案更好但是我们在这里大声笑。它们是正确的,你永远不会添加最长的值。但是你也有其他一些问题。

tie是一个布尔值,所以你不需要== true,只需要(tie){code}

接下来你不能正确地做这个。我知道他们在小学时教会每个人都错了。第一个数字是0你的for循环将总是失去1次写入的方式。 for(int i = 0; i&lt; = 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! ) " );
}