java scanner相關問題

2021-09-10 04:12:55 字數 1574 閱讀 4052

前段時間做資料結構課設,在控制台中進行一些輸入,其中用到了不少scanner的方法,之前沒怎麼注意,導致出現了好多問題,現簡單總結以下:

一、nextint,nextline,next三者區別

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.

讀取包括空格在內的輸入,而且還會讀取行尾的換行字元\n,讀取完成後游標被放在下一行

二、常見問題

1.輸入數字進行選擇功能時,未等繼續輸入,就自動跳下一行

int i;

scanner s=new scanner(system.in);

i=s.nextint();

system.out.println("input yout name")

string name=s.nextline();

system.out.println("input yout ***")

比如,我們輸入數字1並按回車換行,這時,控制台不會等我們輸入name,就直接顯示

input your name

input your ***

原因:nextint()方法只讀取整數,當我們按回車時它並沒有讀取,這個換行符就被string name=s.nextline();語句讀取了,所以出現直接跳過。

解決辦法:

在nextint後買你再加一條s.nextline(),來讀取換行符。

2.當需要輸入多個資料,用空格隔開的時候 ,使用next()會報陣列越界錯誤

原因:next()讀取輸入直到遇見空格。此方法不能讀取被空格分隔開的內容,並且在讀取輸入後把游標留在本行

解決辦法:

使用其他符號進行分割,或者使用nextline();

3.中文輸入出現如,輸入資訊樓,列印輸入內容測試卻為資訊資訊樓,或者xinxi資訊樓等錯誤。

原因:eclipse中文輸入的bug

解決辦法:

1.cmd執行

2.每次輸入時將光標點到下一行。

Java Scanner 用法總結

讀入資料流 scanner sc new scanner systrm.io 從控制台輸入 scanner sc new scanner paths.get filename 獲取檔案path scanner sc new scanner file f 讀入檔案 scanner sc new sca...

showModalDialog相關問題

最近大量地用到了模式視窗,也遇到了不少問題,特總結於此,方便自己日後查閱,若能幫到他人,那就更好了。一 基本使用 語法 vreturnvalue window.showmodaldialog surl varguments sfeatures 引數說明 surl 指定對話方塊要顯示的url。varg...

z index相關問題

1 啟用z index z軸在元素設定position為absolute或relative後被啟用 2 flash的z index問題 瀏覽器解析頁面時,會判斷元素型別,即是否為視窗型別,如果是視窗型別則優先顯示於非視窗型別的元素,顯示在頁面最頂端。flash有個屬性wmode window 視窗 ...