看板 java 關於我們 聯絡資訊
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://www.ptt.cc/bbs/java/M.1440121578.A.40C.html
adrianshum: 因為在stdin輸入 \n 是真的代表一個 '\' 然後 'n' 08/21 10:51
adrianshum: 不是換行 08/21 10:51
matthewyang: @_@ 那 System.in 有跳脫字元嗎 還是 08/21 11:02
matthewyang: 通過 System.in 所有input都會被認定為實際的input? 08/21 11:03
adrianshum: 當然不會有跳脫。 08/21 11:25
matthewyang: 所以System.in是以逐字元方式處理囉?? >_<"a 08/21 11:40
matthewyang: 那我會比較好奇 未什麼用一個String物件接起 08/21 11:41
matthewyang: System.in內容 再new新的Scanner讀取這個String 08/21 11:42
matthewyang: 卻無法判斷這個String內容有\n須要跳行 08/21 11:43
matthewyang: 因為 直接宣告一個String s = "111\naaa"時 08/21 11:43
matthewyang: 可用nextLine() 讀取並分兩行呈現 XDDDD 08/21 11:44
haha02: 編譯時\n會幫你轉成換行字元0x0A 08/21 11:48
matthewyang: 所以 因為System.in的資訊並不會被編譯只會直接傳遞? 08/21 12:04
matthewyang: 大至解了 感謝兩位大大 08/21 12:10