gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:06:45 25 4
gpt4 key购买 nike

我正在处理一个家庭作业问题,该问题要求在同一行上打印第 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 个字符

最佳答案

用户输入也可以包含少于 N 个单词,对吗?首先检查应该是这样。

public static void main(String[] args) {
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(" ");
int n = words.length();
System.out.print("Enter lookup word - N");
int askedFor = input.nextInt();
if (askedFor > n) {
//your logic for this condition
return;
}
String nthWord = words[askedFor-1];
if (nthWord.length() < askedFor) print(nthWord.charAt(nthWord.length()-1));
else print(nthWord.charAt(askedFor-1));
input.close();
}

关于java - 如何打印一行中第 N 个单词的第 N 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com