如何使扫描仪从Java中的一条扫描仪行扫描多个输入?

时间:2019-11-23 16:06:19

标签: java java.util.scanner javahelp

用户应该能够输入5个带有余额的客户的数据。但是,这段代码仅适用于1。我最初考虑使用for或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);

  }
}

2 个答案:

答案 0 :(得分:0)

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个客户名称和余额    约翰    20.0
  • 输入2个客户名称和余额       吉姆       10.0

,依此类推。 我希望这有帮助。如果您问我,您应该使用java.util.ArrayList或java.util.LinkedList。这些类具有许多现成的功能,您不需要像数组那样编写太多代码。

答案 1 :(得分:0)

您要问的不是编码问题,而只是设计问题。 对于按照设计进行的操作,可以按照以下过程或类似方法进行。

  1. 在单行中输入逗号分隔的用户名。
  2. 读取行并拆分名称,现在您有x个客户详细信息,例如一次性读取名称。
  3. 现在您有了名称,对于每种详细信息,请重复上面的1-2,只需输入逗号即可。尝试一次采用一种类型的细节,即,一种类型的细节,例如雇员或部门的薪水。

用于伪代码:

   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. 



    }