简体   繁体   中英

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. 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.

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. For eg

  • Enter 1 customer name and balance John 20.0
  • Enter 2 customer name and balance Jim 10.0

and so on. I hope this helps. If you ask me you should be using java.util.ArrayList or 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.

  1. Enter comma separated user names in single line.
  2. Read the line and split the names, now you have x customers detail like name read in a single shot.
  3. Now you have names, repeat 1-2 above for every type of detail just need to be entered comma separated. Try to take one type of detail at a time, ie one, line one detail like salary of emp or department.

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. 



    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM