0
我很新的這個,在一些ap comp sci問題上工作 我想將用戶輸入存儲到字符串的數組列表中,但是當我打印數組即嘗試填充時,我只是得到類似[,,,]我怎樣才能解決這個問題?如何解決返回空字符串數組的in.nextLine()?
我很新的這個,在一些ap comp sci問題上工作 我想將用戶輸入存儲到字符串的數組列表中,但是當我打印數組即嘗試填充時,我只是得到類似[,,,]我怎樣才能解決這個問題?如何解決返回空字符串數組的in.nextLine()?
你的問題是,在while循環的條件,你讀取用戶輸入鍵入的內容,然後同時裏面你讀我的空行。
您只需要在while內部讀取該行,並在用戶鍵入'exit'時打破循環。具體如下:
public static void main(String[] args) {
System.out.println("Enter words, followed by the word \"exit\"");
Scanner in = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while (true) {
String str = in.nextLine();
if ("exit".equals(str)) {
break;
}
words.add(str);
}
System.out.println(words);
}
感謝了一堆,身份證從未見過的,有很大的幫助:) – ThomasV
「破發」我將不勝感激,如果你能接受的答案,多達投票吧:) – guymaor86