在数组中读取和存储唯一值 (JAVA)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5807447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading and storing unique values in an array (JAVA)
提问by user727694
So i've got a problem in my java homework. The task is to write a program that reads in ten numbers and displays only distinct numbers along with the number of distinct values. what i've got so far is...
所以我的java作业有问题。任务是编写一个程序,读取十个数字并仅显示不同的数字以及不同值的数量。到目前为止我所得到的是......
import java.util.Scanner;
import java.util.Collection;
public class Exercise06_05 {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] list = new int[10];//create my new 10 slot array
//i really want a variable length array but alas
for (int i = 0; i < 10; i++){//get and check the ten input variables
System.out.println("Enter an Integer");//ask for input
int integer = input.nextInt();//assign the input to a temp variable
if (isUnique(list, integer)){//check if the temp is unique to the array
list[i] = integer;//if so assign it
}
}
String output = "";
int j = 0;
for (j = 0; j < list.length; j++){
if(list[j] != 0){//this is where the error accours
output += (list[j] + " ");
}else
break;//this break ensures J doesn't get any higher
//so that i can plug that in for the number of distinct variables
}
System.out.println("The number of distinct numbers is " + j);
System.out.println(output);//print output, and the number of distinct values
}
public static boolean isUnique(int [] arry, int a){// my masterpiece of a method
for (int i = 0; i < (10);){
if (arry [i] == a){//check box
return false;//not unique
} else if (i == (arry.length - 1)){//we done yet?
return true;//if so, return that it's unique
}else//if we're not done increment the box
i++;//there that is
} return false;//now put this here just to safeguard
}
}
It works fine unless the user inputs two of the same ints in a row like 1 and then 1 again. What happens is the program doesn't store the second int, the array keeps a zero and then fails at the create output part. How do i get around this?
除非用户连续输入两个相同的整数,例如 1 然后再次输入 1,否则它工作正常。发生的情况是程序不存储第二个 int,数组保持零,然后在创建输出部分失败。我如何解决这个问题?
采纳答案by Jay
Well, for one thing, if the number you get is unique you insert it into the array. If it is not unique, you don't insert it into the array, but you still advance the array index. Thus, you're going to leave it with the initialization default value of zero.
嗯,一方面,如果您获得的数字是唯一的,则将其插入到数组中。如果它不是唯一的,则不会将其插入到数组中,但仍会推进数组索引。因此,您将保留它的初始化默认值为零。
There's two problems with this.
这有两个问题。
There's no way to distinguish "duplicate value" from "zero". If zero is not a legal value, then okay fine. If zero is legal, this won't work.
More fundamental, when you loop through the array on output, you quit when you hit the first zero. So if the user entered, say, 1,2,4,2,3,4, you're goint to fill your array with 1,2,4,0,3,0. Then when you display the output you're going to write 1,2,4, see the zero and quit, and declare that there are 3 unique values. You'll never reach the 3.
没有办法区分“重复值”和“零”。如果零不是合法值,那么没问题。如果零是合法的,这将不起作用。
更基本的是,当您在输出中循环遍历数组时,您会在遇到第一个零时退出。因此,如果用户输入,例如,1,2,4,2,3,4,您将用 1,2,4,0,3,0 填充您的数组。然后当你显示输出时你要写 1,2,4,看到零并退出,并声明有 3 个唯一值。你永远达不到 3。
I don't know how much they've taught you about the available data structures yet. A better solution would be to use an ArrayList rather than an array, and then only add to the ArrayList when an incoming value is unique. If you haven't learned about that yet, another idea would be to keep a counter of the number of unique values as you go along. Don't insert in the array when you get a duplicate value, and also don't increment the counter. That is, have one counter that's the position in the arrray, which is the same as the number of unique values. Have another counter which is the number of input values read. This will be greater than the position of the array once you see the first duplicate.
我不知道他们已经教了你多少关于可用数据结构的知识。更好的解决方案是使用 ArrayList 而不是数组,然后仅在传入值唯一时才添加到 ArrayList。如果您还没有了解这一点,另一个想法是在您进行过程中保留唯一值数量的计数器。获得重复值时不要插入数组,也不要增加计数器。也就是说,有一个计数器是数组中的位置,它与唯一值的数量相同。有另一个计数器,它是读取的输入值的数量。一旦您看到第一个副本,这将大于数组的位置。
On, on one detail point, not directly related to your question: In your isUnique function, why do you loop up to a hard-coded ten, and then have a separate IF statement to test the array length and break when you reach the end? It would be a lot simpler and easier to read if you coded:
关于一个细节点,与您的问题没有直接关系:在您的 isUnique 函数中,为什么要循环到硬编码的十,然后有一个单独的 IF 语句来测试数组长度并在到达末尾时中断? 如果您编码,它会更简单,更容易阅读:
public static boolean isUnique(int [] arry, int a)
{
for (int i = 0; i < arry.length)
{
if (arry [i] == a)
{
return false; //not unique
}
}
return true; // we made it through without finding a dup, must be unique
}
Or if, as I suggest above, you have a separate variable to say how much of the array is actually filled:
或者,正如我上面所建议的,如果您有一个单独的变量来说明实际填充了多少数组:
public static boolean isUnique(int [] arry, int filled, int a)
{
// filled should always be <=arry.length, but we can check both just to be safe
for (int i = 0; i < arry.length && i<filled)
{
if (arry [i] == a)
{
return false; //not unique
}
}
return true; // we made it through without finding a dup, must be unique
}
回答by u__
Ok this is little different, it's not about answering your question, you already did that, it's about a bit more focus on your solution. You are reading the list of numbers first and then operating on those numbers. Here is another snippet:
好吧,这没什么不同,这不是要回答您的问题,您已经这样做了,而是更多地关注您的解决方案。您首先阅读数字列表,然后对这些数字进行操作。这是另一个片段:
loop = 0;
/**Start Reading your numbers from stdin or anything**/
while(There are numbers to read){
int number = read_number(), counter = 0, found = 0;
while(counter <= loop){
if(a[counter] == number){
found = 1; // you found a match for this number break here
break;
}
counter++;
}
if(found == 0){
/* We did not find our number in array*/
a[counter] = number;
}
}
That's it read only once and loop only once.
那就是它只读取一次并且只循环一次。
回答by CPerkins
Your problem is that you're trying to output more values than are in the array.
您的问题是您试图输出比数组中更多的值。
Doing int[] list = new int[10]
means that list.length will always be 10.
这样做int[] list = new int[10]
意味着 list.length 将始终为 10。
Either switch from an array to a List, or keep track of the number inserted.
从数组切换到列表,或者跟踪插入的数字。
回答by MByD
Even if the value not stored, i is increased by 1.
即使未存储该值,i 也会增加 1。
One solution is:
一种解决方案是:
if (isUnique(list, integer)){//check if the temp is unique to the array
list[i] = integer;//if so assign it
}
else
{
list[i] = 0;
}
Which will store 0 in the cell, otherwise there is nothing (not even 0) in the cell, and the program crashes.
这将在单元格中存储0,否则单元格中什么都没有(甚至没有0),程序就会崩溃。
Instead, if you want to get another value to the cell, decrease i by one instead of assigning 0 to the cell.
相反,如果您想为单元格获取另一个值,请将 i 减一,而不是将 0 分配给单元格。