1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
用戶輸入也可以包含少于 N 個(gè)單詞,對(duì)嗎?首先檢查應(yīng)該是這樣。
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();
}
添加回答
舉報(bào)