Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何一次读取数组的所有元素并确定数组中已经存在的元素?_Java_Arrays - Fatal编程技术网

Java 如何一次读取数组的所有元素并确定数组中已经存在的元素?

Java 如何一次读取数组的所有元素并确定数组中已经存在的元素?,java,arrays,Java,Arrays,使用一维数组解决以下问题: 编写一个输入五个数字的应用程序,每个数字都在10到100之间,包括10和100。读取每个数字时,仅当它不是已读取数字的副本时才显示。规定“最坏情况”,即所有五个数字都不同。使用尽可能小的数组来解决此问题。显示用户输入每个新值后输入的完整唯一值集 我的程序大部分运行良好。我面临的唯一问题是,当我输入数组的第二个元素以检查第一个元素被要求输入时,它会输出“数字不在数组中”。即使数字在数组中。请对我宽容一点,因为我对编程很幼稚 import java.util.Scanne

使用一维数组解决以下问题:
编写一个输入五个数字的应用程序,每个数字都在10到100之间,包括10和100。读取每个数字时,仅当它不是已读取数字的副本时才显示。规定“最坏情况”,即所有五个数字都不同。使用尽可能小的数组来解决此问题。显示用户输入每个新值后输入的完整唯一值集

我的程序大部分运行良好。我面临的唯一问题是,当我输入数组的第二个元素以检查第一个元素被要求输入时,它会输出“数字不在数组中”。即使数字在数组中。请对我宽容一点,因为我对编程很幼稚

import java.util.Scanner;

public class DuplicateElimination {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        // the variable to read the number
        int number = 0;

        // the array with the elements needed to be checked
        int [] array = {12, 33, 54, 90, 100, 1};

        // for loop to ask the question if the number is in the array.
        for(int counter = 0; counter < array.length; counter++ )
        {
            System.out.print("Enter a number to check: ");
            number = input.nextInt();

            if (number == array[counter])
                System.out.printf("The number %d is already in the array.\n\n", array[counter]);


            else
                System.out.printf("The number %d is not in the array.\n\n", number);
        }
    }
}
import java.util.Scanner;
公共类重复消除{
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
//用于读取数字的变量
整数=0;
//包含需要检查的元素的数组
int[]数组={12,33,54,90,100,1};
//for循环询问数字是否在数组中。
用于(int计数器=0;计数器
这不是一个家庭作业,我只是在练习。

使用这个条件:

if (number == array[counter])
您正在评估
number
的当前值是否等于
数组中的单个值。为了评估
number
的值是否存储在
array
中,需要检查
array
中的所有值。下面是一个如何实现的示例:

boolean found = false;
for (int j = 0; j < currentSizeOfArray; j++) {
    if (number == array[j]) {
        found = true;
        break;
    }
}
if (found) {
    //do something
}
boolean-found=false;
对于(int j=0;j

解决家庭作业的另一个提示是:使用
while
循环读取数据,而不是
for
循环。另外,还有一个时态变量,用于维护数组中当前的元素数,与数组的长度不相同。

数组已经满了,您已经创建了5个条目。你确定这不是家庭作业吗?因为你的代码与你的问题陈述不匹配。