I was trying to solve the following question in java .
Maya buys “N” no of products from a shop. The shop offers a different percentage of discount on each item. She wants to know the item that has the minimum discount offer, so that she can avoid buying that and save money.
[Input Format: The first input refers to the no of items; the second input is the item name, price and discount percentage separated by comma(,)]
Assume the minimum discount offer is in the form of Integer.
Note: There can be more than one product with a minimum discount.
Sample Input 1:
4
mobile,10000,20
shoe,5000,10
watch,6000,15
laptop,35000,5
Sample Output 1:
shoe
Explanation: the discount on the mobile is 2000, the discount on the shoe is 500, the discount on the watch is 900 and the discount on the laptop is 1750. So the discount on the shoe is the minimum.
I got this error in my code .but everthing is looking good so I coundn't able to find the bug.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Main.main(Main.java:24)
The error is in the following code block.
for(int i=0;i<n;i++)
{
discount[i]=(Integer.parseInt(input1[i][2])*Integer.parseInt(input1[i][1]))/100;
}
Here is the Full code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
String input[]=new String[n];
String input1[][]=new String[n][3];
for(int i=0;i<n;i++)
{
input[i]=sc.nextLine();
input1[i]=input[i].split(",");
}
int discount[]=new int[n];
for(int i=0;i<n;i++)
{
discount[i]=(Integer.parseInt(input1[i][2])*Integer.parseInt(input1[i][1]))/100;
}
int min_d=32767; //highest value that int can store;
for(int i=0;i<n;i++)
{
if(min_d>discount[i])
min_d=discount[i];
}
String output=new String();
for(int i=0;i<n;i++)
{
if(discount[i]==min_d)
output+=input1[i][0]+" ";
}
System.out.println(output);
}
}