[英]How to make scanner scan multiple inputs from one scanner line in java?
The user should be able to input data of 5 customers with balances.用户应该能够输入 5 个有余额的客户的数据。 However this piece of code only works for 1. I initially thought of using a for OR a while loop but I think they will create the display message 5 times.然而,这段代码只适用于 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);
}
So, in the above code the display message prints 5 times but every time it will be for different customers.因此,在上面的代码中,显示消息打印了 5 次,但每次都是针对不同的客户。 For eg例如
and so on.等等。 I hope this helps.我希望这有帮助。 If you ask me you should be using java.util.ArrayList or java.util.LinkedList.如果你问我你应该使用 java.util.ArrayList 或 java.util.LinkedList。 These classes come with many features out of the box and you need not code much as in the case of arrays.这些类具有许多开箱即用的功能,您不需要像数组那样编写太多代码。
You are asking is not a coding problem but just a matter of design.您问的不是编码问题,而只是设计问题。 For what you are doing as per design you can follow below process or similar.对于您按照设计所做的工作,您可以遵循以下流程或类似流程。
for pseudo code:对于伪代码:
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.