2014-10-16 99 views
2

我現在很難解決這個問題。 所以,我有這個代碼片斷,詢問用戶的3個輸入。掃描儀輸入跳過下一個輸入

case 0: 
     String accnum,pin,name; 
     System.out.print("Enter account name: "); 
     name = input.nextLine(); 
     System.out.print("Enter account number: "); 
     accnum = input.next(); 
     System.out.print("Enter account PIN: "); 
     pin = input.next(); 
     atm.set_accinfos(name,accnum,pin); 
     //System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n"); 
    break; 

但每次我運行它,它總是跳過輸入字符串「名字」,我嘗試使用input.next();就可以了,但它現在會跳過字符串「accnum」的輸入。

編輯:它也恰好發生如果從「名稱」的輸入上有一個空間,例如:約翰·多伊。

我在這裏錯過了什麼嗎?

+1

你是否在這段代碼之前使用同一個掃描器? – 2014-10-16 14:08:03

+0

@LukeWillis - 其實這是一個很好的觀點。 – TheLostMind 2014-10-16 14:09:58

回答

0

試試這個。我認爲next()的問題。因爲接下來的讀取輸入與默認分隔符令牌(我認爲空間是默認的分隔符):

case 0: 
String accnum,pin,name; 

System.out.print("Enter account name: "); 
name = input.nextLine(); 

System.out.print("Enter account number: "); 
accnum = input.nextLine(); 

System.out.print("Enter account PIN: "); 
pin = input.nextLine(); 

atm.set_accinfos(name,accnum,pin); 
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n"); 
break; 
+0

後沒有碰到任何東西,我編輯了原始帖子,問題只存在,如果我在字符串「名稱」上輸入了一個字符串上有空格 – 2014-10-16 14:09:27

+0

你試過我的代碼@ScratchFever。 – Karunakar 2014-10-16 14:13:44

+0

是的,它仍然跳過它 – 2014-10-16 14:41:22

1

nextLine()吞掉帳號PIN碼next()產生的換行符(當您敲入回車鍵時)。所以,它不會要求名稱。在pin = input.next();後加input.nextLine()並嘗試

+0

嘗試,它仍然跳過「accnum」 – 2014-10-16 14:06:42

+0

@ScratchFever - 然後使用nextLine()'無處不在:P。舊的答案應該起作用。輸入數字和引腳後,你是否輸入密碼?即2次? – TheLostMind 2014-10-16 14:07:42

+0

不,我在輸入 – 2014-10-16 14:20:38

0

如果您使用input的代碼塊之前的任何地方,那麼你需要一定要早叫nextLine上。

如果您改爲使用next,那麼您的輸入流仍將包含一個新的行字符(\n)。因此,當您使用nextLine開始此代碼塊時,該呼叫將採用先前的\n而不是剛輸入的名稱。

一般來說,如果您的Scanner正在閱讀System.in,那麼您應該在任何地方都使用nextLinenext,nextInt,其他下一個方法是爲了更可預測的數據。

0

好吧,這對於大家的幫助,我設法通過添加「input.nextLine();」來解決它。之前「name = input.nextLine();」