[英]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 次,但每次都是針對不同的客戶。 例如
等等。 我希望這有幫助。 如果你問我你應該使用 java.util.ArrayList 或 java.util.LinkedList。 這些類具有許多開箱即用的功能,您不需要像數組那樣編寫太多代碼。
您問的不是編碼問題,而只是設計問題。 對於您按照設計所做的工作,您可以遵循以下流程或類似流程。
對於偽代碼:
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.