作者matthewyang (馬特休斯)
看板java
標題[J2SE] 關於System.in的問題請教
時間Fri Aug 21 09:46:10 2015
OK 事情是這樣的
小的是Java新手,發神經在嘗試input String時, 有了下列疑問:
====== Code Part ======
Scanner sc = new Scanner(System.in);
String strInput = sc.nextLine();
如果輸入 12345\nabcde
輸出為 12345\nabcde
若改成
String s = "12345\nabcde";
Scanner sc1 = new Scanner(s);
System.out.println(sc1.nextLine());
System.out.println(sc1.nextLine());
輸出會變成:
12345
abcde
傻呼呼的將第一段改成
Scanner sc = new Scanner(System.in);
String strInput = sc.nextLine();
Scanner sc2 = new Scanner(strInput);
System.out.println(sc2.nextLine());
System.out.println(sc2.nextLine());
輸入12345\nabcde時,輸出同樣是12345\nabcde
印象中, newxLine() 與 next() 主要差異是遇到空白或挑脫字元(\n)時,
是否接續到讀取到敲enter的點
但System.in在收到input內容有\n時,卻無法如預期跳行
還請神人指點小的觀念上的誤判點
Orz... (先行跪拜)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.120.196.138
※ 文章網址: https://webptt.com/m.aspx?n=bbs/java/M.1440121578.A.40C.html
1F:→ adrianshum: 因為在stdin輸入 \n 是真的代表一個 '\' 然後 'n' 08/21 10:51
2F:→ adrianshum: 不是換行 08/21 10:51
3F:→ matthewyang: @_@ 那 System.in 有跳脫字元嗎 還是 08/21 11:02
4F:→ matthewyang: 通過 System.in 所有input都會被認定為實際的input? 08/21 11:03
5F:→ adrianshum: 當然不會有跳脫。 08/21 11:25
6F:→ matthewyang: 所以System.in是以逐字元方式處理囉?? >_<"a 08/21 11:40
7F:→ matthewyang: 那我會比較好奇 未什麼用一個String物件接起 08/21 11:41
8F:→ matthewyang: System.in內容 再new新的Scanner讀取這個String 08/21 11:42
9F:→ matthewyang: 卻無法判斷這個String內容有\n須要跳行 08/21 11:43
10F:→ matthewyang: 因為 直接宣告一個String s = "111\naaa"時 08/21 11:43
11F:→ matthewyang: 可用nextLine() 讀取並分兩行呈現 XDDDD 08/21 11:44
12F:推 haha02: 編譯時\n會幫你轉成換行字元0x0A 08/21 11:48
13F:→ matthewyang: 所以 因為System.in的資訊並不會被編譯只會直接傳遞? 08/21 12:04
14F:→ matthewyang: 大至解了 感謝兩位大大 08/21 12:10