我正在解决一个家庭作业问题,要求在同一行上打印第 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 个字符
1 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
用户输入也可以包含少于 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();
}
添加回答
举报
0/150
提交
取消