程序读取七个整数值,并打印出每个值的出现次数。

huangapple go评论75阅读模式
英文:

Program to read seven integer values and print out the number of occurrences of each value

问题

正如标题所示,我试图输入7个整数,并能够输出这些整数以及其中有多少个重复的。

使用以下代码:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int[] userInput = new int[7];
  System.out.print("输入七个数字:");
  for (int i = 0; i < 7; i++) {
    userInput[i] = input.nextInt();
  }
  for (int i = 0; i < 7; i++) {
    int duplicates = 0;
    for (int j = 0; j < 7; j++) {
      if (userInput[i] == userInput[j])
        duplicates++;
    }
    System.out.println("数字 " + userInput[i] + " 出现 " + duplicates + " 次。");
  }
}

使用输入:12 23 44 22 23 22 55

我得到了重复的输出,如下所示:

数字 12 出现 1 次
数字 23 出现 2 次
数字 44 出现 1 次
数字 22 出现 2 次
数字 23 出现 2 次
数字 22 出现 2 次
数字 55 出现 1 次

为了清晰起见,我所追求的是:

数字 12 出现 1 次
数字 23 出现 2 次
数字 44 出现 1 次
数字 22 出现 2 次
数字 55 出现 1 次

我感激任何建议。

英文:

as the title suggests, i'm trying to input 7 integers and be able to output those integers along with a count for how many duplicates there were among them.

Using the code:

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int[] userInput = new int[7];
  System.out.print(&quot;Enter seven numbers: &quot;);
  for (int i = 0; i &lt; 7; i++) {
    userInput[i] = input.nextInt();
  }
  for (int i = 0; i &lt; 7; i++) {
    int duplicates = 0;
    for (int j = 0; j &lt; 7; j++) {
      if (userInput[i] == userInput[j])
        duplicates++;
    }
    System.out.println(&quot;Number &quot; + userInput[i] + &quot; occurs &quot; + duplicates + &quot; times.&quot;);
  }
}

with the input: 12 23 44 22 23 22 55

I keep getting duplicates in my output, like so:

Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.

For clarity, what i'm aiming for is:

Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times

I appreciate any and all suggestions.

答案1

得分: 1

你可以使用一个向量来存储每个数字的出现次数

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print("输入七个数字:");
    for (int i = 0; i < 7; i++) {
        userInput[i] = input.nextInt();
    }

    int duplicates[] = new int[7];
    for (int i = 0; i < 7; i++)
        duplicates[i] = 0;

    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 7; j++) {
            if (userInput[i] == userInput[j])
                duplicates[i]++;
        }
        System.out.println("数字 " + userInput[i] + " 出现 " + duplicates[i] + " 次。");
    }
}

输入 12 23 44 22 23 22 55 的输出将会是:

数字 23 出现 2 次。
数字 44 出现 1 次。
数字 22 出现 2 次。
数字 23 出现 2 次。
数字 22 出现 2 次。
数字 55 出现 1 次。

<details>
<summary>英文:</summary>

    
You can use a vector to store all occurs for each number

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print(&quot;Enter seven numbers: &quot;);
    for (int i = 0; i &lt; 7; i++) {
      userInput[i] = input.nextInt();
    }

    int duplicates[] = new int[7];
    for(int i = 0; i &lt; 7; i++)
       duplicates[i] = 0;

    for (int i = 0; i &lt; 7; i++) {
      for (int j = 0; j &lt; 7; j++) {
        if (userInput[i] == userInput[j])
          duplicates[i]++;
      }
      System.out.println(&quot;Number &quot; + userInput[i] + &quot; occurs &quot; + duplicates[i] + &quot; times.&quot;);
    }
    }
The output for the input `12 23 44 22 23 22 55` will be:

    Number 23 occurs 2 times.
    Number 44 occurs 1 times.
    Number 22 occurs 2 times.
    Number 23 occurs 2 times.
    Number 22 occurs 2 times.
    Number 55 occurs 1 times.

</details>



# 答案2
**得分**: 1

```java
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print("请输入七个数字:");
    for (int i = 0; i < 7; i++) {
        userInput[i] = input.nextInt();
    }

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i : userInput) {
        if (map.containsKey(i))
            map.put(i, map.get(i) + 1);
        else
            map.put(i, 1);
    }

    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        System.out.println("数字 " + entry.getKey() + " 出现 " + entry.getValue() + " 次。");
    }
}
英文:
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);
	int[] userInput = new int[7];
	System.out.print(&quot;Enter seven numbers: &quot;);
	for (int i = 0; i &lt; 7; i++) {
		userInput[i] = input.nextInt();
	}

	Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;();
	for (int i : userInput) {
		if (map.containsKey(i))
			map.put(i, map.get(i) + 1);
		else
			map.put(i, 1);
	}

	for (Map.Entry&lt;Integer, Integer&gt; entry : map.entrySet()) {
		System.out.println(&quot;Number &quot; + entry.getKey() + &quot; occurs &quot; + entry.getValue() + &quot; times.&quot;);
	}
}

答案3

得分: 0

目前,该程序计算数组中每个数字的出现次数,这就是重复数字正在进行重复努力。

实现您所尝试做的有不同的方法,其中一种直接的方式是,将数字存储在一个映射中,将数字作为键,值作为1,并在再次遇到相同数字时递增。

英文:

Currently, the program calculates occurrence of each digit in an array and that's where duplicate digits its doing duplicate efforts.

There are different ways of achieving what you are trying to do, the straight forward way could be, store the numbers in a map, which key as number and value as 1, and increment whenever the same digit is encountered again.

答案4

得分: 0

使用排序的方法:

Arrays.sort(userInput);
for (int i = 0; i < userInput.length;) {
    int count = 1;
    int j = i + 1;
    while (j < userInput.length && userInput[i] == userInput[j]) {
        j++;
        count++;
    }

    System.out.println("数字 " + userInput[i] + " 出现 " + count + " 次");
    i = j;
}

这将将时间复杂度降低到 O(N log N)。

你可以进一步使用 HashMap 将其优化到 O(N)。

英文:

There are couple of ways:

Using sorting:

    Arrays.sort(userInput);
    for(int i=0;i&lt;userInput.length;){
     int count = 1;
     int j = i + 1;
     while(j &lt; userInput.length &amp;&amp; userInput[i] == userInput[j]{
      j++; count++;
    }
    
    System.out.println(&quot;Number &quot;+userInput[i]+&quot; occurs &quot;+count +&quot; times&quot;);
     i = j;
    }

This will reduce the time complexity to O(N log N)

you can further improve this till O(N) using HashMap

答案5

得分: 0

使用 HashMap

Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i : userInput) {
    Integer j = hm.get(i);
    hm.put(i, (j == null) ? 1 : j + 1);
}

for (Map.Entry<Integer, Integer> val : hm.entrySet()) {
    System.out.println("Number " + val.getKey() + " occurs " + val.getValue() + " times.");
}
英文:

use HashMap

Map&lt;Integer, Integer&gt; hm = new HashMap&lt;Integer, Integer&gt;(); 
for (int i : userInput) {
    Integer j = hm.get(i); 
    hm.put(i, (j == null) ? 1 : j + 1); 
}

for (Map.Entry&lt;Integer, Integer&gt; val : hm.entrySet()) {
    System.out.println(&quot;Number &quot; + val.getKey() + &quot; occurs &quot; + val.getValue() + &quot; times.&quot;);
}

答案6

得分: 0

你可以通过使用**HashMap<Integer, Integer>**来实现相同的功能,如下所示:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print("Enter seven numbers: ");
    for (int i = 0; i < 7; i++) {
        userInput[i] = input.nextInt();
    }

    HashMap<Integer, Integer> numberCountMap = new HashMap<>();
    for(int element : userInput){
        numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
    }
    numberCountMap.forEach((key, value) -> System.out.println("Number " + key + " occurs " + value + " times."));
}
英文:

You can do the same By using HashMap<Integer, Integer> as shown below.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print(&quot;Enter seven numbers: &quot;);
    for (int i = 0; i &lt; 7; i++) {
        userInput[i] = input.nextInt();
    }

    HashMap&lt;Integer, Integer&gt; numberCountMap = new HashMap&lt;&gt;();
    for(int element : userInput){
        numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
    }
    numberCountMap.forEach((key, value) -&gt; System.out.println(&quot;Number &quot; + key + &quot; occurs &quot; + value + &quot; times.&quot;));
}

答案7

得分: 0

以下是翻译好的部分:

首先,将 j 更改为 j = i+1,因为您不需要额外的迭代来确认 array[i]==array[i]

第二件事是将结果存储在一个 Map<digit, occurrences> 中,并在方法结束时从映射中打印出来。

for (int i = 0; i < 7; i++) {
    int duplicates = 1;
    for (int j = i+1; j < 7; j++) {
        if (userInput[i] == userInput[j])
            duplicates++;
    }
    map.put(i, duplicates);
}
英文:

My approach would be -

First of all to change j to j = i+1 because you dont need an extra iteration to confirm that array[i]==array[i].

Second thing is to store the results in a Map&lt;digit , occurances&gt; and print from the map at the end of the method.

for (int i = 0; i &lt; 7; i++) {
int duplicates = 1;
for (int j = i+1; j &lt; 7; j++) {
  if (userInput[i] == userInput[j])
    duplicates++;
}
map.put(i , duplicates);

答案8

得分: 0

以下是翻译好的部分:

"更有效的方法是将这些数字存储在一个 Map 中。"

假设您的输入是 12 23 44 22 23 22 55

void duplicates(){
    
    // 获取输入并将其存储在列表中
    Scanner input = new Scanner(System.in);
    List<Integer> numbers = input.nextLine().split(" ");

    // 将值存储到映射中
    HashMap<Integer, Integer> numbersMap = new HashMap<>();
    for(int number : numbers){
        // 如果映射已包含该数字,则将其出现次数增加一
        // 否则将其存储到映射中,值为 1
        int newValue = numbersMap.containsKey(number) ? numbersMap.get(number) + 1 : 1;
        numbersMap.put(number, newValue);
    }

    // 打印结果
    numbersMap.forEach((k, v) -> {
        System.out.println(String.format("数字 %d 出现了 %d 次。", k, v));
    });
}
英文:

It would be more efficient to store the numbers in a Map.

Assuming your input is 12 23 44 22 23 22 55

void duplicates(){
    
    //acquire input and store it in a List
    Scanner input = new Scanner(System.in);
    List&lt;Integer&gt; numbers = input.nextLine().split(&quot; &quot;);

    //store the values into a map
    HashMap&lt;Integer, Integer&gt; numbersMap = new HashMap&lt;&gt;();
    for(int number : numbers){
        //if the map contains the number already, then increase it&#39;s occurence by one
        //otherwise store it into the map with the value of 1
        int newValue = numbersMap.containsKey(number) ? numbersMap.get(number) + 1 : 1;
        numbersMap.put(number, newValue);
    }

    //print results
    numbersMap.forEach((k, v) -&gt; {
        System.out.println(String.format(&quot;The number %d occured %d times.&quot;, k, v));
    });
}

答案9

得分: 0

你可以使用流(streams)以非常简洁的方式来实现这个:

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class IntegerCounter {
    public static Map<Integer, Long> countOccurrences(int[] input) {
        return Arrays.stream(input)
                .boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}

这里是一个演示使用的测试案例:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Map;

public class IntegerCounterTests {
    @Test
    public void shouldReturnCorrectCount() {
        int[] input = {12,23,44,22,23,22,55};
        Map<Integer, Long> expectedResult = Map.of(12, 1L, 23, 2L, 44, 1L, 22, 2L, 55, 1L);
        Map<Integer, Long> result = IntegerCounter.countOccurrences(input);

        result
                .entrySet()
                .stream()
                .forEach(e -> System.out.println(String.format("Number %d occurs %d times.", e.getKey(), e.getValue())));

        Assertions.assertEquals(expectedResult, result);
    }
}

除了添加断言来验证结果是否符合预期外,我还添加了显示标准输出的行:

Number 22 occurs 2 times.
Number 55 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 12 occurs 1 times.
英文:

You can implement this in a very clean way using streams:

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class IntegerCounter {
    public static Map&lt;Integer, Long&gt; countOccurences(int[] input) {
        return Arrays.stream(input)
                .boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    }
}

Here is a test case that demonstrates it's usage:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Map;

public class IntegerCounterTests {
    @Test
    public void shouldReturnCorrectCount() {
        int[] input = {12,23,44,22,23,22,55};
        Map&lt;Integer, Long&gt; expectedResult = Map.of(12, 1L, 23, 2L, 44, 1L, 22, 2L, 55, 1L);
        Map&lt;Integer, Long&gt; result = IntegerCounter.countOccurences(input);

        result
                .entrySet()
                .stream()
                .forEach(e -&gt; System.out.println(String.format(&quot;Number %d occurs %d times.&quot;, e.getKey(), e.getValue())));

        Assertions.assertEquals(expectedResult, result);
    }
}

Next to an assertion to verify that the result is indeed what you want I also added the lines to show the output to standard out:

Number 22 occurs 2 times.
Number 55 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 12 occurs 1 times.

答案10

得分: 0

这是你的代码:

List<Integer> values = new ArrayList<>();

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] userInput = new int[7];
    System.out.print("Enter seven numbers: ");
    
    for (int i = 0; i < 7; i++) {
        userInput[i] = input.nextInt();
    }
    
    for (int i = 0; i < 7; i++) {
        if (!values.contains(userInput[i])) {
            int duplicates = 0;
            
            for (int j = 0; j < 7; j++) {
                if (userInput[i] == userInput[j])
                    duplicates++;
            }
            
            System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
            values.add(userInput[i]);
        }
    }
}

在这里,我创建了一个名为values的整数列表,用于存储已经出现过的值。然后,我在循环中检查values列表是否已经包含了当前用户输入的值,如果没有包含,就执行重复次数的计算,并将该值添加到values列表中。这样可以避免重复计算和输出。

英文:

You already handled the hard part. The only thing you should do is, putting writed values to a list, and if list contains the next value, simply, not to write this value again
this is your code :
`

public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  int[] userInput = new int[7];
  System.out.print(&quot;Enter seven numbers: &quot;);
  for (int i = 0; i &lt; 7; i++) {
    userInput[i] = input.nextInt();
  }
  for (int i = 0; i &lt; 7; i++) {
    int duplicates = 0;
    for (int j = 0; j &lt; 7; j++) {
      if (userInput[i] == userInput[j])
        duplicates++;
    }
    System.out.println(&quot;Number &quot; + userInput[i] + &quot; occurs &quot; + duplicates + &quot; times.&quot;);
  }
}

`

and this is the code, i modified a bit

List&lt;Integer&gt; values = new ArrayList&lt;&gt;();       
public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      int[] userInput = new int[7];
      System.out.print(&quot;Enter seven numbers: &quot;);
      for (int i = 0; i &lt; 7; i++) {
        userInput[i] = input.nextInt();
      }
      for (int i = 0; i &lt; 7; i++) {
            if(!values.contains(userInput[i]){
             int duplicates = 0;

                 for (int j = 0; j &lt; 7; j++) {
                        if (userInput[i] == userInput[j])
                               duplicates++;
                               }
          System.out.println(&quot;Number &quot; + userInput[i] + &quot; occurs &quot; + duplicates + &quot; times.&quot;);
values.add(userInput[i]);
}
      }
    }

here, the list creation of me, can be wrong. But i think you got the idea.
Good luck

huangapple
  • 本文由 发表于 2020年10月12日 17:25:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64315084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定