我正在尝试计算数组中存在唯一数字的次数,使用的索引数量取决于输入的元素数量。除了 1 之外,它主要是可操作的。第一个值没有被考虑在内。循环正在检查arrays.length -1
,所以即使我输入了 3 两次,数字 3 也显示为 1 的计数。我知道解决这个问题的最好方法是运行一个不使用的循环,arrays.length -1
但是我无法将一个条目与它旁边的条目进行比较if(a[i] == a[i + 1] && a[i] != 0)
看看是否有不止一次出现的值。我认为最好的办法是将计数值与其对应的被计数的数组值一起存储在我的计数方法中,然后在该方法之外执行一个 for 循环,这可能吗?我看不到这样做的方法,因为我对 java 还很陌生。可以给我一些指导吗:)
import java.util.Scanner;
public class Prac_ExeOne
{
static int count = 1;
static int numberUsed = 0; // static its used to show its a class wide variable and there is only one copy.
static int[] Array = new int [50]; // the maximum elements inside the array that can be used is 10;
int size;
public int fillArray(int[] a)
{
System.out.println("Enter up to " + a.length + " nonnegative numbers.");
System.out.println("Mark the end of the list with a negative number.");
Scanner keyboard = new Scanner(System.in);
int next;
int index = 0;
next = keyboard.nextInt();
while ((next >= 0) && (index < a.length ))
{
numberUsed++;
a[index] = next;
index++;
// Print out each value of next
System.out.println(next);
next = keyboard.nextInt();
//System.out.println("Number of indexes used" + numberUsed);
}
keyboard.close(); // close the keyboard so it can't continue to be used.
return index;
}
public int[] sort(int[] arrays)
{
for(int i = 0;i < arrays.length -1 ;i++ )
{
int store = 0;
// Move Larger Values to the right.
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
// Sort swapped smaller values to the left.
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
return arrays;
}
public void count(int[] a)
{
//for each element in array go through if conditons.
System.out.println("N " + "Count");
for(int i = 0;i < a.length -1;i++)
{
if(a[i] == a[i + 1] && a[i] != 0)
{
count++;
}
if(a[i] != a[i+1])
{
count = 1;
}
if (a[i] != 0)
{
System.out.println(a[i] + " " + count);
}
}
}
public static void main(String[] args)
{
Prac_ExeOne score = new Prac_ExeOne();
score.fillArray(Array);
score.sort(Array);
score.count(Array);
}
}
输入:
Enter up to 50 nonnegative numbers.
Mark the end of the list with a negative number.
3
3
2
2
-2
输出:
N Count
3 1
2 2
2 1
期望的结果:
简而言之,我希望程序正确计算值,然后在 N 下方的左侧显示该值,并将其在数组中的次数显示在 Count 下方