gpt4 book ai didi

Java将错误的数据写入数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:04 25 4
gpt4 key购买 nike

我正在实现算法,该算法将计算链接列表中唯一数字的出现次数。问题出在 for 循环中,当输入类似于 1 1 1 2 2 2

时,我正在计算出现次数

而不是获取输出

1 appearance 3 times
2 appearance 3 times

我懂了

1 appearance 3
0 appearance 0

使用输入1 2 3 4 5 6 7 8 9我得到了数组超出索引的异常。这是代码

public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner user_input = new Scanner(System.in);
String input = user_input.nextLine();
//Getting user input, if the user enter an empty line(enter, enter) the loop will die
while(input.length() > 0){
list.add(Integer.parseInt(input));
input = user_input.nextLine();
}
Collections.sort(list); //sorting the input
//Getting the number of unique numbers
int count_of_unique_numbers = 1;// There will be atleast one unique number

if(!list.isEmpty()){
int temp = list.get(0);
for(int i = 1;i < list.size(); i++){
if(temp != list.get(i)){
count_of_unique_numbers++;
temp = list.get(i);
}
}
}
else{
System.out.println("The list is empty");
return;
}
//Counting how many times the unique numbers apper;
int number_appearance[][] = new int[count_of_unique_numbers][2];
int temp = list.get(0);
int counter = 1;
int j = 0;
for(int i = 1;i < list.size();i++){
if(temp == list.get(i)){ counter++; }
else{
number_appearance[j][0] = temp;
number_appearance[j][1] = counter;
counter = 1;
temp = list.get(i);
j++;
}
}
//Printing the number_appearance array
for(int i = 0; i < count_of_unique_numbers; i++){
System.out.println("The number: " + number_appearance[i][0] + " appearece " + number_appearance[i][1] + " times");
}
}

最佳答案

您可以将所有这些简单地归结为这一点。

Map < String, Integer > numMap = new HashMap < String, Integer > ();
Scanner user_input = new Scanner(System. in );
String input = user_input.nextLine();

String[] inputArray = input.split(" ");
for (String s: inputArray) {
if (numMap.containsKey(s)) {
numMap.put(s, numMap.get(s) + 1);
} else {
numMap.put(s, 1);
}
}

for (Map.Entry < String, Integer > entry: numMap.entrySet()) {
System.out.println("number: " + entry.getKey() + " appeared: " + entry.getValue() + " times");
}

关于Java将错误的数据写入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27947673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com