繁体   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