用户应该能够输入 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 个客户姓名和余额 约翰 20.0
- 输入 2 个客户姓名和余额 吉姆 10.0
等等。 我希望这有帮助。如果你问我你应该使用 java.util.ArrayList 或 java.util.LinkedList。这些类具有许多开箱即用的功能,您不需要像数组那样编写太多代码。
关于java - 如何使扫描仪从java中的一个扫描仪行扫描多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59009523/