java - 读取和存储数组中的唯一值(JAVA)

标签 java arrays unique

所以我的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


       }

   }

它工作正常,除非用户连续输入两个相同的整数,例如 1,然后再次输入 1。发生的情况是程序不存储第二个 int,数组保留零,然后在创建输出部分失败。我该如何解决这个问题?

最佳答案

好吧,这有点不同,这不是回答你的问题,你已经这样做了,而是更多地关注你的解决方案。您首先阅读数字列表,然后对这些数字进行操作。 这是另一个片段:

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;
    }
}

也就是说它只读取一次并且只循环一次。

关于java - 读取和存储数组中的唯一值(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5807447/

相关文章:

java - 将类对象转换为 Wicket 中的模型

javascript - Node.js 使用 readline 填充数组并使用

r - 如何计算每组中唯一名称的数量

c++ - 保存数组地址的指针地址如何相同?

c - 使用C语言从数组中删除重复项

database - 如何确保文档中的字段在 ArangoDB 中是唯一的?

java - 运行 jar 文件中的 perl 脚本文件

java - 避免 JMS/ActiveMQ 上的重复消息

java - Spring Boot 数据源设置

javascript - 迭代数组中未定义的方法