如何打印一行中第 N 个单词的第 N 个字符?

我正在解决一个家庭作业问题,要求在同一行上打印第 N 个字符和第 N 个单词,不带空格。如果第 N 个单词太短并且没有第 N 个字符,则程序将打印该单词的最后一个字符。如果用户输入空词(简单地按下),则该词将被忽略。


(我们还没有学习方法,所以我不应该使用它们)


请参阅下面的代码,我不确定如何让我的代码打印该单词的最后一个字符(如果它没有第 N 个字符)。


import java.util.Scanner;


public class Words {


    public static void main(String[] args) {

        final int N=5;

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a line of words seperated by spaces ");

        String userInput = input.nextLine();

        String[] words = userInput.split(" ");

        String nthWord = words[N];


        for(int i = 0; i < nthWord.length();i++) {

            if(nthWord.length()>=N) {

                char nthChar = nthWord.charAt(N);

                System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar);

            }

            if(nthWord.length()<N) {

                    char nthChar2 = nthWord.charAt(nthWord.length()-1);

                    System.out.print("The " + N + "th word in the line entered is " + nthWord + "The " + N + "th charecter in the word is " + nthChar2);

        }

        input.close();

    }


}

}

当我运行这个时,我收到一个错误:


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

    at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)

    at java.base/java.lang.String.charAt(String.java:702)

    at Words.main(Words.java:24)

我希望在同一行看到第 N 个单词和第 N 个字符


PIPIONE
浏览 75回答 1
1回答

胡子哥哥

用户输入也可以包含少于 N 个单词,对吗?首先检查应该是这样。public static void main(String[] args) {&nbsp; &nbsp; Scanner input = new Scanner(System.in);&nbsp; &nbsp; System.out.print("Enter a line of words seperated by spaces ");&nbsp; &nbsp; String userInput = input.nextLine();&nbsp; &nbsp; String[] words = userInput.split(" ");&nbsp; &nbsp; int n = words.length();&nbsp; &nbsp; System.out.print("Enter lookup word - N");&nbsp; &nbsp; int askedFor = input.nextInt();&nbsp; &nbsp; if (askedFor > n) {&nbsp; &nbsp; &nbsp; &nbsp; //your logic for this condition&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; String nthWord = words[askedFor-1];&nbsp; &nbsp; if (nthWord.length() < askedFor) print(nthWord.charAt(nthWord.length()-1));&nbsp; &nbsp; else print(nthWord.charAt(askedFor-1));&nbsp; &nbsp; input.close();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java