簡體   English   中英

java - 如何使掃描儀從Java中的一個掃描儀行掃描多個輸入?

[英]How to make scanner scan multiple inputs from one scanner line in java?

用戶應該能夠輸入 5 個有余額的客戶的數據。 然而,這段代碼只適用於 1。我最初想到使用 for OR a while 循環,但我認為他們會創建顯示消息 5 次。

import java.util.Scanner;

public class Assignment {

 public static void main (String [] args) {

 Scanner scan = new Scanner (System.in);
 Customer c [] = new Customer [5];
 Customer hold;
 String name; int count = 0;
 double totalBalance = 0.0;

 System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
 String name = scan.next();
 double balance = scan.nextDouble();

 c [count++]= new Customer(name,balance);

 System.out.println("Search for all customers who have more than $100");

  for (int i=0; i<count ; i++){
  if (c[i].getBalance()>100) 
  System.out.println(c[i].getName());

  totalBalance += balance;
  averageBalance = totalBalance/5;

  System.out.println("The average balance is: "+averageBalance);

  }
}
System.out.println("For 5 customers enter the name and in the next line the balance"); // displays the message to user
for(int i=0; i<5; i++){
    String name = scan.next();
    double balance = scan.nextDouble(); 
    c [count++]= new Customer(name,balance);
}

因此,在上面的代碼中,顯示消息打印了 5 次,但每次都是針對不同的客戶。 例如

  • 輸入 1 個客戶名稱並余額 John 20.0
  • 輸入 2 個客戶名稱和余額 Jim 10.0

等等。 我希望這有幫助。 如果你問我你應該使用 java.util.ArrayList 或 java.util.LinkedList。 這些類具有許多開箱即用的功能,您不需要像數組那樣編寫太多代碼。

您問的不是編碼問題,而只是設計問題。 對於您按照設計所做的工作,您可以遵循以下流程或類似流程。

  1. 在單行中輸入逗號分隔的用戶名。
  2. 閱讀該行並拆分名稱,現在您有 x 個客戶詳細信息,例如一次讀取的名稱。
  3. 現在你有了名字,對每種類型的細節重復上面的 1-2 只需要輸入逗號分隔。 嘗試一次獲取一種類型的詳細信息,即一個,一行一個詳細信息,例如 emp 或部門的工資。

對於偽代碼:

   private String[] getDetails(BuffferReader reader){
// read a line at a time, using readline function    
// using readed line/console input, split it on comma using split() function and return array of values. 



    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM