gpt4 book ai didi

java - 循环查找数组中的唯一数字时遇到逻辑错误

转载 作者:行者123 更新时间:2023-12-01 16:28:30 25 4
gpt4 key购买 nike

这是我的 Java 类教科书中的一个问题,其中用户输入 10 个整数。该程序应该读取所​​有整数,并且仅将唯一数字(不重复)显示为输出。

-运行时输出为: 输入 10 个数字:1 2 3 2 1 6 3 4 5 2 不同数字的数量为 5 不同的数字是:1 2 3 0 0

-当它真的应该是: 输入 10 个数字:1 2 3 2 1 6 3 4 5 2 不同数字的数量为 5 不同的数字是:1 2 3 6 4 5

由于我们处于类(class)的早期阶段并且了解该语言,因此我们的任务是使用嵌套循环来完成此任务。任何帮助,将不胜感激。

import java.util.Scanner;

public class chapter7e5 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
//create Scanner

System.out.print("Enter 10 numbers: ");

int[] numberArray = new int[10];
//create array for all numbers

int[] distinctArray = new int[10];
//create array for distinct numbers

int distinct = 0;

for (int i = 0; i < 10; i++)
//for loop to have user enter numbers and put them into array

numberArray[i] = input.nextInt();

distinctArray[0] = numberArray[0];
//first value will be distinct

for (int i = 1; i < numberArray.length; i++) {
//loop to go through remaining values in numberArray

boolean exists = false;
//create boolean

for (int j = 0; j < distinctArray.length; j++) {
//loop to check if value exists already in distinctArray

if (numberArray[i] == distinctArray[j]) {

exists = true;
//if value does already exists, then exist = true

break;
//break out of inner loop

}
}

if (exists == false) {
//if value is unique then add it to the distinct array

distinctArray[i] = numberArray[i];

distinct++;
//increment variable distinct

}
}
//}

System.out.println("The number of distinct numbers is " + distinct);

System.out.print("The distinct numbers are: ");

for (int k = 0; k < distinct; k++)

System.out.print(distinctArray[k] + " ");

}

}

最佳答案

我有以下建议:

  • 将外循环中的每个数字numbArray赋值给testNumber
    例如int testNumber = numbArray[i];

  • 在内循环中,检查没有其他数字等于testNumber。请注意,
    i == j时,测试并未完成,因为该数字是分配给testNumber的数字

     if (i != j && numberArray[j] == testNumber) {
exists = true;
break;
}
  • 然后在 if 子句中确定是否分配号码,您可以这样做
  if (!exists) {
// if value is unique then add it to the distinct array
distinctArray[distinct++] = testNumber;
}

请注意,通常的做法是不显式测试 boolean 值是否为 true 或
false。由于 if 语句根据 true 或 false 条件进行计算,因此您可以只使用
值。所以 exists 表示它存在,而 !exists 表示它不存在

关于java - 循环查找数组中的唯一数字时遇到逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62108124/

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