官方解釋:
nextInt(): it only reads the int value,?nextInt() places the cursor in the same line?after reading the input.
next():read the input only till the space. It can't read two words separated by space. Also, next() places the?cursor in the same line?after reading the input.
nextLine():reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the?cursor in the next line.
此處号阿,cursor意思為光標并鸵。
可以看出nextInt()和next() 讀取到空格時就會結(jié)束讀取,不管有沒有回車扔涧,nextInt()對應(yīng)int類型园担,next()對應(yīng)字符串類型
可以看出nextLine() 是可以讀取到空格的,只有當(dāng)它讀取到回車的時候才會結(jié)束
當(dāng)nextInt()或next()與nextLine() 同時使用時:
可見當(dāng)nextInt()或next()與nextLine() 一起使用時枯夜,因為nextInt()和next() 只會讀取有效數(shù)值或字符串弯汰,剩下的"\n"(回車)還沒有讀取,并將光標放在本行中湖雹,而nextLine()則會讀取"\n"(回車)咏闪,把光標移到下一行并結(jié)束輸入。
當(dāng)遇到空格時結(jié)束摔吏。若輸入中有空格鸽嫂,此時nextLine()相當(dāng)于讀取從前面留下的數(shù)據(jù)開始的后面的內(nèi)容,因此輸出的時候會帶有空格征讲。
若想在nextInt()或next()后讀取一行溪胶,需要加一行sc.nextLine(),相當(dāng)于讓sc.nextLine()讀取掉上一行輸入的回車(可以理解為消耗掉)稳诚,此時下一行的nextLine()才會繼續(xù)接受輸入哗脖。
不建議nextInt()或next()與nextLine()混用,可都用nextLine()扳还,不過讀數(shù)字時需要使用Integer的parseInt方法將字符串轉(zhuǎn)成int