モリーマクドノウ:
私は、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番目の文字を見ることを期待します
ヨーゲッシュKaushikによる:
ユーザ入力はまた、右、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();
}