public class A6{
public static void main(String[] args){
String personInfo[][]={
{"Anderson", "Varejao", "1125"},
{"Giorgi", "Tevzadze", "1125"},
{"Will", "Cherry", "1225"},
{"Kevin", "Love", "2525"},
{"Kyrie", "Livings", "454"},
{"Dion", "Malborg", "6250" }
};
//max - who has the highest salary
if(args[0].equals("max")){
int max = Integer.parseInt(personInfo[0][2]);
for(int i = 0; i < personInfo.length; i++) {
int l = Integer.parseInt(personInfo[i][2]);
if(max < l){
max = l;
}
}
for(int i = 0; i < personInfo.length; i++) {
if(max == Integer.parseInt(personInfo[i][2])){
System.out.println(personInfo[i][0]);
}
}
System.out.println("His sallary is:" +max );
// va ZZZ - who has the closest salary to value ZZ
if(args[0].equals("va")){
for(int iž0; i < personInfo.length; i++{
int l = Integer.parseInt(personInfo[i][2]);
...
}
}
}
我已经写了一个找到工资最高的人的方法,现在我正在努力找到与我输入的值最接近的工资。例如:我进入命令行java A6 456,应该从命令行Kyrie Livings得到答案。我已经开始通过编写for循环并将字符串值从personInfo转换为int来完成此操作。有什么建议吗?
答案 0 :(得分:1)
试试这个:(考虑到内存使用没有限制):
int index = 0, minDiff = 0, diff = 0;
for(int i = 0;i<personInfo.length;i++){
diff = Math.abs(personInfo[i][2] - inputVal);
if(diff<minDiff){
minDiff = diff;
index = i;
}
}
return personInfo[index][2];
inputVal
是您要传递给此函数的参数,您要为其找到最近的工资。您可以修改此逻辑以满足此用例的需求。