首页 > 解决方案 > 显示字符串没有第 6 个字符时出现问题

问题描述

我一直无法识别两个字符串的第 6 个字符。到目前为止,我编写的代码在两个字符串都有一个时显示第 6 个字符。但是,如果他们不这样做,程序就会崩溃。尽管使用了布尔值,但它仍然没有正常工作。如果有人可以提供一些关于如何修复它的提示,这对于像我这样的新手来说将是一个巨大的帮助。谢谢!

这是代码(更具体地说是方法);

    //Method sixString
       public static void sixString() {
     boolean found = false;

    //The character at index 5 (6th character) of the first string is stored in p
    char p = str1.charAt(5);

    //The character at index 5 (6th character) of the second string is stored in q
    char q = str2.charAt(5);

    if (found == true) {
        //Display the 6th character of the first string
        System.out.println("The 6th character of the first string is: " + p);


        //Display the 6th character of the second string
        System.out.println("The 6th character of the second string is: " + q);
    }

    if (found == false) {
        //Display that there is no 6th character of the first string
        System.out.println(" Sorry! There is no 6th character in the first string ");

        //Display that there is no 6th character of the second string
        System.out.println(" Sorry! There is no 6th character in the second string ");
    }


//Method sixString()
}

1)如果两个字符串都有第6个字符,则显示每个字符串中的字符(这个已经完成)

2) 如果一个字符串有第 6 个字符而另一个没有,则显示该字符串的字符并向用户显示另一个字符串没有的消息(对此感到困惑;可能需要提示)

3) 如果两个字符串都没有,则显示它们都没有(这是程序崩溃的地方)

标签: java

解决方案


在使用超出字符串边界的索引调用之前,您需要检查输入字符串的长度.charAt(),否则您将收到异常。

if (str1.length() >= 6) {
    char p = str1.charAt(5);
    System.out.println("The 6th character of the first string is: " + p);
} else {
    System.out.println(" Sorry! There is no 6th character in the first string ");
}

推荐阅读