2016-11-30 8 views
0

最初にブール値を作成し、それをtrueに設定して最初の実行を有効にします。その後の実行はユーザー入力に基づいています。異なるプリミティブ型の入力行を取得する方法

boolean emptyLine = true; 
      String name; int quantity; double price; 

Scanner scan = new Scanner(System.in); 

     while(emptyLine != false) //repeatedly request user input if input is not empty 
     { 
     //ask the user for the quantity of items being purchased. 
     System.out.println("Enter name of item: Enter quantity of item purchased: Enter price of item being purchased: "); 
     input = scan.nextLine(); //should read the line of input 

     item =       //name of item from the line of input. 
     quantity = scan.nextInt();  //should get the quantity from the line of input 
     price = scan.nextDouble();  //get the price from the line of input 

     if(input.length() >= 0) 
     { 
      emptyLine = true; 
     } 
     else 
     { 
      emptyLine = false; 
     } 

     } 

ユーザー入力が空であるかどうかを確認するコードを作成しようとしています。ユーザ入力が空である場合、ユーザは有効な入力または終了を入力するように要求される。

例えば、ユーザーがスペースを入力した場合、プログラムはそれを受け入れるようにしますが、ユーザーがENTERボタンを押した場合は却下されます。

+0

'item = quantity = scan.nextInt()'は目的に合っていますか? PS: 'input.length()> = 0'はあなたが必要とするブーリアンを与え、if-elseの必要はありません – AxelH

+0

行全体を' input'に読み込むので、その文字列を解析する必要があります。 tokenizer、正規表現などを使用してください。 – Thomas

+0

あなたは本当に 'Scanner#hasNextLine()'を見てください。また、あなたはおそらく[this](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo)の問題 – TheLostMind

答えて

0

一つの簡単な方法:

while (scann.hasNextLine()) { 
    String userInput = scan.nextLine(); 

今、ユーザ入力は文字列です。 を手動でにチェックしてください。たとえば、を呼び出してisEmpty()を呼び出します。空でない場合は、次に予想されるタイプに変換しようとすることができます。

+0

は動作しません...それ以前に試しました – Atinuke

+0

「うまくいかない」とはどういう意味ですか?その問題の説明は、他の人があなたを助けてくれるようにしたいときには機能しません。 – GhostCat

+0

scan.hasNextLine(); – Atinuke

関連する問題