当尝试对同一个值计数两次时,循环不正确并且超出了HashMap的界限



下面的代码接受用户输入(int值(,然后找到重复的偶数计数。

2个问题:

  1. 如果您的输入中有2 7 19 8看起来像2、2、2和8。为什么我无法
    理解
  2. 我放置list.get(intNum)+1以计算值的哈希映射部分两次出界。如果没有它,它就会运行。我该怎么数两次

提前感谢。

public class Various {
static Scanner userinput= new Scanner(System.in);
static int nums;
static int big;//will be used to find bug number in array
public static void main(String[] args) {
List<Integer> list= new ArrayList<>();//for all numbers
List<Integer> listEven= new ArrayList<>(); //just for evens
Map<Integer,Integer> hmap= new HashMap<Integer,Integer>(); //number count
System.out.println("Enter some numbers: ");
nums=userinput.nextInt();
big=nums;
int evenNumber;
list.add(nums);
while(userinput.hasNextInt()){
nums=userinput.nextInt();
//below part of the code finds biggest value
if(nums>big){
big=nums;
}
//Above part of the code finds biggest value
list.add(nums);
//below part of the code finds/prints duplicate value
for(int i=0;i<list.size()-1;i++){           
for(int j=i+1;j<list.size();j++){
if(list.get(i)==list.get(j)){
System.out.println("Duplicate " + list.get(j));
}
}
//Above part of the code finds/prints duplicate value
}
//below part of the code finds even numbers
for(int i=0;i<list.size();i++){
//for loop will start from 0 till user input            
if(list.get(i)%2==0){
//if any of those i values%2=0 those will be Even and I will capture those
listEven.add(list.get(i));
}
//Above part of the code finds even numbers
}
//below part of the code finds number occurrence count          
for(Integer intNum: list){
if(!(hmap).containsKey(intNum)){
hmap.put(intNum, 1);
}else{
//below part to take care if a number comes twice i add 1 more(+1)
hmap.put(intNum, list.get(intNum)+1);
}   
//Above part of the code finds number occurrence count  
}
}
System.out.println("Values are " + list);
System.out.println("Biggest value " + big);
System.out.println("Even numbers " + listEven);
System.out.println("Numbers in list and occurance " + hmap);
}
}

问题A:

在代码中,您有一个while循环,用于检查数字,但每次用户输入数字时,您都会循环查看数字列表并检查偶数。

最合乎逻辑的方法是更改代码,以便在用户输入所有数字后检查偶数。或者你可以添加这个,这是一个较小的解决方案,但它会起作用:


listEven.add(list.get(i));

将上面的代码更改为下面的代码。

if (!listEven.contains(list.get(i))) {
listEven.add(list.get(i));
}

问题B:

错误在于这个代码:

// below part of the code finds number occurrence count
for (Integer intNum : list) {
if (!(hmap).containsKey(intNum)) {
hmap.put(intNum, 1);
} else {
// below part to take care if a number comes twice i add 1
// more(+1)
hmap.put(intNum, list.get(intNum) + 1);
}
// Above part of the code finds number occurrence count
}

您正在尝试执行list.get(intNum),但是方法get需要索引,而不需要您试图查找的值。我认为您的意思是键入hmap.get(intNum)而不是list.get(intNum),这将正确更新计数。

最新更新