我完全难过了。我休息了几个小时,我似乎无法想出这个。这令人心烦意乱!
我知道我需要检查数组中的当前元素,看看它是否出现在数组的其他位置。想法是输出以下内容:
要求用户输入10个整数,并将这些整数分配给数组(因此“数字”作为方法的参数)。假设我输入“1,1,2,3,3,4,5,6,7,8”。打印结果应为“1次发生2次.2次发生1次.3次发生2次.4次发生1次.5次发生1次.6次发生1次.7次发生1次.8次发生1次。”该打印将以单独的方法完成。
我的代码中的所有内容都有效,除了我为计算出现次数而创建的此方法。
public static int getOccurrences(int[] numbers)
{
int count = 0;
for (int i = 0; i < numbers.length; i++)
{
int currentInt = numbers[i];;
if (currentInt == numbers[i])
{
count++;
}
}
return count;
}
我知道这里的问题是什么。我将数组中的当前整数元素设置为变量currentInt。 if语句计算数组中的每个整数元素,因此输出为“[I @ 2503dbd3发生10次”。
如何跟踪数组中每个元素的出现次数?
答案 0 :(得分:6)
package countoccurenceofnumbers;
import java.util.Scanner;
public class CountOccurenceOfNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] num = new int[100];
int [] count = new int[100];
//Declare counter variable i
//and temp variable that will
//temporarily hold the value
//at a certain index of num[] array
int i,temp = 0;
System.out.println("Enter the integers between 1 and 100: ");
//Initialize num[] array with user input
for(i=0; i < num.length; i++){
num[i] = input.nextInt();
//expected input will end when user enters zero
if(num[i] == 0){
break;
}
}//end of for loop
//value at a given index of num array
//will be stored in temp variable
//temp variable will act as an index value
//for count array and keep track of number
//of occurences of each number
for(i = 0; i < num.length; i++){
temp = num[i];
count[temp]++;
}//end of for looop
for(i=1; i < count.length; i++){
if(count[i] > 0 && count[i] == 1){
System.out.printf("%d occurs %d time\n",i, count[i]);
}
else if(count[i] >=2){
System.out.printf("%d occurs %d times\n",i, count[i]);
}
}//end of for loop
}//end of main
}//end of CountOccurrenceOfNumbers
/////////// OUTPUT //////////////////////
输入1到100之间的整数:
2 5 6 5 4 3 23 43 2 0
2发生2次,3次发生1次,4次发生1次,5次 发生2次,6次发生1次,23次发生1次,43次 发生1次成功成功(总时间:3分23秒)
答案 1 :(得分:3)
@NYB你几乎是对的,但你必须输出计数值,并在每次元素检查时从零开始。
int count=0,currentInt=0;
for (int i = 0; i < numbers.length; i++)
{
currentInt = numbers[i];
count=0;
for (int j = 0; j < numbers.length; j++)
{
if (currentInt == numbers[j])
{
count++;
}
}
System.out.println(count);
}
@loikkk我稍微调整了你的代码,以便为每个元素打印出来。
int[] a = { 1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1 };
Arrays.sort(a);
int nbOccurences = 1;
for (int i = 0, length = a.length; i < length; i++) {
if (i < length - 1) {
if (a[i] == a[i + 1]) {
nbOccurences++;
}
} else {
System.out.println(a[i] + " occurs " + nbOccurences
+ " time(s)"); //end of array
}
if (i < length - 1 && a[i] != a[i + 1]) {
System.out.println(a[i] + " occurs " + nbOccurences
+ " time(s)"); //moving to new element in array
nbOccurences = 1;
}
}
答案 2 :(得分:2)
你需要两个循环:
您要去哪里
一个嵌套循环,作为你当前所在位置前面的一个索引,除非你在最后。
你的阵列中是否有一个你不想要的号码?如果是这样,请使用该值(例如-1)作为标记值,以便在计算时覆盖您的出现次数。然后,当您再次浏览数组以查找下一个数字时,如果它具有您的标记值,则跳过它。
答案 3 :(得分:2)
您可以找到问题的答案here
我在我的示例中使用了Arrays.sort()
方法:
public class MyTest {
/**
* @param args
*/
public static void main(String[] args) {
int[] a = {1, 9, 8, 8, 7, 6, 5, 4, 3, 3, 2, 1};
Arrays.sort(a);
int nbOccurences = 0;
for (int i = 0, length = a.length - 1; i < length; i++) {
if (a[i] == a[i + 1]) {
nbOccurences++;
}
}
System.out.println("Number same occurences : " + nbOccurences);
}
}
答案 4 :(得分:0)
您需要对数组中的数字顺序进行排序。您可以使用'sort()'
方法,将您的数字从最小到最大组织。
您还需要两个循环,一个用于与另一个进行比较。或者在我的解决方案中,我使用了&#39; while声明&#39;然后是&#39; for循环&#39;。
如果我解决问题的方法是您正在寻找的,我不知道。也许有更短和/或更好的方法来解决这个问题。这就是我想到的方式。祝你好运!
public static int getOccurrences(int[] numbers){
Array.sort (numbers); //sorts your array in order (i,e; 2, 9, 4, 8... becomes, 2, 4, 8, 9)
int count = 0;
int start = 0;
int move = 0;
while(start < numbers.length){
for (int j = 0; j < numbers.length; j++){
int currentInt = numbers[start];;
if (currentInt == numbers[j])
{
count++;
move++;
}
}
if(count == 1){
return ("Number : " + numbers[start] + " occurs " + count + " time ");
} else {
return ("Number : " + numbers[start] + " occurs " + count + " times ");
}
count = 0;
start = start + move;
move = 0;
}
}
答案 5 :(得分:0)
只需复制并执行它,就可以避免在数组中出现整数。
public class noOfOccurence{
public static void main(String[] args){
int a[] = {1,9,4,5,6,7,5,6,7,3,2,5,7,9,0,4,3,5,1,4,6,0,2,3,1,4,3,8};
HashSet<Integer> al = new HashSet<Integer>();
//Store the array in set as set will store unique elemnets
for(int i=0;i<a.length;i++){
//int count =0;
al.add(a[i]);
}
//printing the set
System.out.println("al "+al);
for(int set : al){
int count = 0;
for(int j=0;j<a.length;j++){
if(set==a[j]){
count++;
}
}
System.out.println(set+" occurs "+count+" times");
}
}
}
答案 6 :(得分:0)
import java.util.Scanner;
public class array2 {
public static void main (String[]args) {
Scanner input = new Scanner (System.in);
int [] number = new int [101];
int c;
do {
System.out.println("Enter the integers from 1-100");
c = input.nextInt();
number[c]++;
}while (c != 0);
for(int i = 0; i < number.length ; i++) {
if (number[i] !=0) {
if (number[i] == 1)
System.out.println(i + " occurs " + number[i] + " time");
else
System.out.println(i + " occurs " + number[i] + " times ");
}
}
}
}
答案 7 :(得分:0)
最有效的方法是创建哈希图,以在迭代数组时保存元素的出现。它将以2n的时间复杂度完成此任务,这是解决此问题的最佳方法-
HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
int count;
for(int i=0;i<arr.length;i++){
if(hmap.get(arr[i])==null){
hmap.put(arr[i],1);
}else{
count=hmap.get(arr[i]);
count++;
hmap.put(arr[i],count);
}
}
答案 8 :(得分:0)
//我使用列表来解决问题。这不是一种简洁的方法
公共静态列表>发生(int []个卡){
// first, we create a ArrayList to store the distinct number and its corresponding count value
//it takes time
List<List<Integer>> element = new ArrayList<>();
int tmp=cards[0], count=0;
int total = cards.length;
for(int i=0; i < total; i++) {
if(i == total -1) {
if( cards[i] == tmp) {
List<Integer> l = new ArrayList<>();
l.add(tmp);
l.add(count+1);
element.add(l);
break;
}else {
List<Integer> l = new ArrayList<>();
l.add(tmp);
l.add(count);
element.add(l);
l = new ArrayList<>();
l.add(cards[i]);
l.add(1);
element.add(l);
break;
}
}
if(cards[i] == tmp) {
count++;
}else {
List<Integer> l = new ArrayList<>();
l.add(tmp);
l.add(count);
element.add(l);
tmp = cards[i];
count = 1; //we already have 1 occurence of cards[i]. i.e. tmp
}
}
return element;
}
答案 9 :(得分:0)
我们可以使用Java 8 Stream API创建频率图
Stream.of("apple", "orange", "banana", "apple") .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.forEach(System.out::println);
下游操作本身就是对String类型的元素进行操作的收集器(Collectors.counting())。 并产生Long类型的结果。 collect方法调用的结果是一个Map。
这将产生以下输出:
香蕉= 1
orange = 1
apple = 2
答案 10 :(得分:0)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// This program counts the number of occurrences of error message. It read the data from Excel sheet for the same.
public class fileopen {
public static void main(String[] args) {
String csvFile = "C:\\Users\\2263\\Documents\\My1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
List<String> list = new ArrayList<String>();
String[] country = null;
Map<String, Integer> hm = new HashMap<String, Integer>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
country = line.split(cvsSplitBy);
list.add(country[2]);
System.out.println(country[1]);
}
for (String i : list) {
Integer j = hm.get(i);
hm.put(i, (j == null) ? 1 : j + 1);
}
// displaying the occurrence of elements in the arraylist
for (Map.Entry<String, Integer> val : hm.entrySet()) {
if(val.getKey().equals("Error Message")){
System.out.println(val.getKey());
continue;
}
System.out.println(val.getKey() + " " + val.getValue());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
答案 11 :(得分:-2)
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
//Array fr will store frequencies of element
int [] fr = new int [arr.length];
int visited = -1;
for(int i = 0; i < arr.length; i++){
int count = 1;
for(int j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}