Java代码实现:查找list中的数字与目标数最接近的数,打印出来,急求?
展开全部
public static void main(String args[]){
int target = 584;
ArrayList<明蠢String> array = new ArrayList<String>激颤陪();
String string = "洞高wodf125bbsdfa36sfgsfd580";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
array.add(matcher.group());
}
int need = Integer.valueOf(array.toArray()[0].toString());
int frag = Math.abs(need- target);
for(int i = 0; i< array.size(); i++){
int temp = Math.abs(Integer.valueOf(array.toArray()[i].toString()) - target);
if(temp < frag){
frag = temp;
need = Integer.valueOf(array.toArray()[i].toString());
}
}
System.out.println("need="+need);
}
int target = 584;
ArrayList<明蠢String> array = new ArrayList<String>激颤陪();
String string = "洞高wodf125bbsdfa36sfgsfd580";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
array.add(matcher.group());
}
int need = Integer.valueOf(array.toArray()[0].toString());
int frag = Math.abs(need- target);
for(int i = 0; i< array.size(); i++){
int temp = Math.abs(Integer.valueOf(array.toArray()[i].toString()) - target);
if(temp < frag){
frag = temp;
need = Integer.valueOf(array.toArray()[i].toString());
}
}
System.out.println("need="+need);
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
list.add(i);
}
// 接近的数字
int nearNum = 6;
// 差值实始化
int diffNum = Math.abs(list.get(0) - nearNum);
// 最终结果
int result = list.get(0);
for (Integer integer : list)
{
int diffNumTemp = Math.abs(integer - nearNum);
if (diffNumTemp < diffNum)
{
diffNum = diffNumTemp;
result = integer;
}
}
System.out.println(result);
for (int i = 0; i < 10; i++)
{
list.add(i);
}
// 接近的数字
int nearNum = 6;
// 差值实始化
int diffNum = Math.abs(list.get(0) - nearNum);
// 最终结果
int result = list.get(0);
for (Integer integer : list)
{
int diffNumTemp = Math.abs(integer - nearNum);
if (diffNumTemp < diffNum)
{
diffNum = diffNumTemp;
result = integer;
}
}
System.out.println(result);
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询