Converting input to multiple ints / vars

waynekenoff

i am running into a problem while making ints / vars. While knowing how many input numbers there are, i can make a code like:

Scanner in = new Scanner(System.in);
int[] vars = new int[8];
for(int z = 0; z < vars.length; z++)
  vars[z] = in.nextInt();

But the problem is that i don't know how many inputs there are going to be. The task in short is to recommend buyer to which product they should buy, so first two input numbers will be how many products there are and how many customers there are. Next X inputs will be prices of the products and next Y inputs will be the amount of money customers have. And all of that has to be in the same input.

Shortly: I need to make a code that automatically names inputs to ints, depending how many input numbers there are.

Could I name inputs depending on the line? Example:

input
5 5
1 5 8 11 12
10 5 9 12 13

Edit: Could also someone ( @Noixes / @Raju Sharma ) give me a little tip how could I start managing with those inputs to find the best solution to every client? So every client would buy the item of his money or less(closest to the amount of his money)? After one client buys the item. The item would still be on the shop at the same price.

Raju Sharma

If you are using java 8 then below code would help you in single line, without knowing size of arrays.

 Scanner in = new Scanner(System.in);
 int[] productsAndCustomers = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
 int[] productsPrices = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); 
 int[] customersMoney = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(productsAndCustomers));
System.out.println(Arrays.toString(productsPrices));
System.out.println(Arrays.toString(customersMoney));

Input:

5 5

1 5 8 11

10 5 9 12

Output in arrays list:

[5, 5]

[1, 5, 8, 11]

[10, 5, 9, 12]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related