gpt4 book ai didi

java - 如何一次读取数组的所有元素并确定数组中已存在的内容?

转载 作者:行者123 更新时间:2023-12-02 05:07:12 25 4
gpt4 key购买 nike

Use a one-dimensional array to solve the following problem:
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.

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

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

P.S 这不是作业,我这样做只是为了保持练习。

最佳答案

使用此条件:

if (number == array[counter])

您正在评估number 的当前值是否等于array 内的单个值。为了评估number的值是否存储在array中,就是检查array中的所有值。以下是如何实现它的示例:

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

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

关于java - 如何一次读取数组的所有元素并确定数组中已存在的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com