检查一些已经在一个阵列中使用的Java [英] to check if a number have already been used in a array java

查看:108
本文介绍了检查一些已经在一个阵列中使用的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接听的评论:
是的,我知道我没有搜索任何东西。我不知道怎么了,那种原因我在这里
不,我不需要你写从我的code,只需告诉我它是怎么做的,所以我可以学习
我曾尝试不同的东西,但不想乱了我的code的东西,没有工作。

问题:我需要检查,如果输入已经被使用过,如果不是我想将它添加到阵列中,如果不是我想再问

 扫描仪键盘=新的扫描仪(System.in);的System.out.println(什么是数组的长度?);
INT lengde = keyboard.nextInt();
INT [] myArray的=新的INT [lengde]
的for(int i = 0; I< lengde;我++){
  的System.out.println(第(i + 1)+(给一个号码));
  INT使用= keyboard.nextInt();  //如果在使用前已经添加
   //的System.out.println(选择一个新号码);  // //其他使用前没有被添加
    myArray的[我] =使用;}
对于(INT I:myArray的)
  的System.out.println(ⅰ);keyboard.close();


解决方案

检查情况如下最简单的方式:

 的for(int i = 0; I< lengde;){
  INT的readInt = keyboard.nextInt();
  布尔发现= FALSE;
  对于(INT指数= 0;指数 - LT;我;指数++){
    intFromArray = myArray的[指数] //从数组元素
    如果(==的readInt intFromArray){
      发现= TRUE; //号码已在阵
      打破;
    }
  }
  //在数组中没有发现的数量。将它添加到阵列。
  如果(!找到){
    myArray的[I] =的readInt;
    我++;
  }其他{
       的System.out.println(阵中找到再试一次......。);
  }}

您可能希望允许一定数量的唯一的尝试,否则会无限循环。

Answering the comments: Yes, I do know I have not searched for anything. I don't know how, kind of the reason I am here No, I don't need you to write the code from me, simply show me how it is done so I can learn I have tried different things, but did not want to mess my code with things that did not work

question: I need to check if the input have been used before, If not I want to add it to the array, if not I want to ask again.

Scanner keyboard = new Scanner(System.in);

System.out.println("What's the length of the array?");
int lengde = keyboard.nextInt();                   
int[] myArray = new int[lengde]; 


for (int i = 0; i < lengde; i++) {
  System.out.println((i+1) + (" give a number"));
  int used = keyboard.nextInt(); 

  //if  used have been added before
   // System.out.println("pick a new number");

  //else // used have not been added before
    myArray[i] = used;

} 
for (int i : myArray)
  System.out.println(i);

keyboard.close();

解决方案

The simplest way to check would be as follows:

for (int i = 0; i < lengde; ) {
  int readInt = keyboard.nextInt();
  boolean found = false;
  for(int index=0; index < i; index++) {
    intFromArray = myArray[index]; // Get element from array
    if(readInt == intFromArray) {
      found = true; // Number already in array
      break;
    }
  }
  // Number not found in the array. Add it to the array.
  if(!found) {
    myArray[i] = readInt;
    i++;
  } else {
       System.out.println("Found in array. Try again...");
  }

}

You might want to allow a certain number of tries only, otherwise it will loop indefinitely.

这篇关于检查一些已经在一个阵列中使用的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆