my data1=[{"iphone6","16000"},{"iphone7","17000"},{"iphone8","10000"}]
i want my output as iphone8 ,10000 but it giving exception Index 0 out of bounds for length 0 error
public String getMinLaptopPrice(ArrayList<String[]> data) {
//min value
String min = data.get(0)[1];
for(int i=0;i<data.size();i++) {
String cur = data.get(i)[1];
int S = cur.compareTo(min);
if(S>0) {
min = cur;
}
}
return min;
}
You are using the wrong compare method,for int value,you can compare the value directly
public String getMinLaptopPrice(ArrayList<String[]> data) {
int s = Integer.parseInt(data.get(0)[1]);
String min = data.get(0)[0];
for(int i=1;i<data.size();i++) {
int value = Integer.parseInt(data.get(i)[1]);//convert string to int vlaue
if(value<s) {
min = data.get(i)[0];
s= value;
}
}
return min;
}
The reason for the Exception is the initialization of the min
variable. Set it to Integer.MAX_VALUE and parse the data. On zero length arrays you can't access the data.
Generally
Finding maximum: init at min value
Check array size ahead of accessing.
you can try this code
public Integer getMinLaptopPrice(ArrayList<String[]> data) {
int min = Integer.valueOf(data.get(0)[1]);
for (int i = 0; i < data.size(); i++) {
int cur = Integer.valueOf(data.get(i)[1]);
if (cur < min) {
min = cur;
}
}
return min;
}
in your code, you try to compare two string Object instead of there value... so i convert all amount data into Integer
and compare minimum value by if condition... and also change method return type to Integer
...
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String[] d1 = {"iphone6","16000"};
String[] d2 = {"iphone7","17000"};
String[] d3 = {"iphone8","10000"};
ArrayList<String[]> data1=new ArrayList<>();
data1.add(d1);
data1.add(d2);
data1.add(d3);
String[] d = getMinLaptopPrice(data1);
System.out.print(d[0] + ", " + d[1]);
}
public static String[] getMinLaptopPrice(ArrayList<String[]> data) {
int value_min = Integer.parseInt(data.get(0)[1]);
String key_min = "";
for(int i = 1; i < data.size(); i++) {
int value = Integer.parseInt(data.get(i)[1]);
if (value < value_min) {
value_min = value;
key_min = data.get(i)[0];
}
}
String[] d = {key_min, String.valueOf(value_min)};
return d;
}
}
and the output is:
iphone8, 10000
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.