Home » Java » How to take Multiple values input(with different types and separated with comma) from user in java-Exceptionshub

How to take Multiple values input(with different types and separated with comma) from user in java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to accept multiple values from user like productName,Price,gstAmount like this:

sample input:2 //System.out.println("enter no of products");
mobile,2356,15
watch,200,10

After this calculate the item with minimum price

sample output:watch
How to&Answers:

Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter no of products: ");
        int np = Integer.parseInt(in.nextLine());
        String productName, minPricedProduct = "", input;
        String[] inputArr;
        int price, gst, grossPrice;    
        int min = Integer.MAX_VALUE;
        for (int i = 1; i <= np; i++) {
            System.out.print("Enter Product name, Price, GST amount (like productname,1234,123): ");
            input = in.nextLine();
            inputArr = input.split(",");
            productName = inputArr[0];
            price = Integer.parseInt(inputArr[1]);
            gst = Integer.parseInt(inputArr[2]);
            grossPrice = price + gst;
            if (grossPrice < min) {
                min = grossPrice;
                minPricedProduct = productName;
            }
        }
        System.out.println(minPricedProduct);
    }
}

A sample run:

Enter no of products: 3
Enter Product name, Price, GST amount (like productname,1234,123): spectacles,4500,125
Enter Product name, Price, GST amount (like productname,1234,123): watch,200,10
Enter Product name, Price, GST amount (like productname,1234,123): mobile,2356,15
watch

Note: You should treat this program as a guide and try to improve it e.g. I’ve not done exception handling deliberately so that you can do it yourself and learn further.

Answer:

Follow these steps:

  1. Use a scanner to read in the 3 values from the user, after each ask if they wish to enter another item, if yes then loop else close scanner

  2. for each entry store in an object with 3 fields for name, price, gst, then add to array

  3. sort array in order of price and pick lowest

Answer:

You can use BufferedReader or Scanner class to read from console. After which you you can sort to get the lowest priced item.