gpt4 book ai didi

java - 读入十个数字并显示不同数字的数量以及以一个空格分隔的不同数字的程序

转载 作者:行者123 更新时间:2023-11-30 06:50:48 25 4
gpt4 key购买 nike

我知道这个问题之前已经被问过,但不是以我正在编写代码的格式..刚刚开始学习java类(class),所以我不熟悉任何复杂的java..下面的代码基本上包括我所知道的所有java。请帮忙!提前致谢。

import java.util.Scanner;
public class problem2try {

public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;

//input
System.out.print("Please enter in 10 integers: ");

for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}

//processing
distinctArray[0] = inputList[0];
for (int i = 1; i < inputList.length; i++)
{
for (int j = 0; j < inputList.length; j++)
{
if (inputList[i] == inputList[j])
{
counter++;
continue;
}
else
{
distinctArray[i] = inputList[i];
}
}
}

//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<distinctArray.length; x++)
{
if (distinctArray[x] != 0)

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

最佳答案

你在“处理” block 中的逻辑似乎不正确。我修改它以检查当前数字(外循环)到所有已知数字(内循环)。如果未找到匹配项,则会将其附加到已知数字列表中,并且计数会递增。

我还修改了“输出”代码以打印已知数字列表中的第一个计数器数字。超过该索引的值未初始化。

import java.util.Scanner;
public class problem2try {

public static void main(String[] args) {
//declarations
Scanner keyboard = new Scanner (System.in);
int [] inputList = new int [10];
int [] distinctArray = new int [10];
int num;
int counter = 0;

//input
System.out.print("Please enter in 10 integers: ");

for (int i = 0; i < inputList.length; i++)
{
num = keyboard.nextInt();
inputList[i] = num;
}

//processing
for (int i = 0; i < inputList.length; i++)
{
boolean found = false;
for (int j = 0; j < counter; j++)
{
if (inputList[i] == distinctArray[j])
{
found = true;
break;
}
}
if (!found)
{
distinctArray[counter++] = inputList[i];
}
}

//output
System.out.println("The number of distinct numbers is " + counter);
System.out.print("The distict numbers are: ");
for (int x=0; x<counter; x++)
{
System.out.print(distinctArray[x] + " ");
}
}
}

关于java - 读入十个数字并显示不同数字的数量以及以一个空格分隔的不同数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42825397/

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