gpt4 book ai didi

java - 数组和输出

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:45:34 24 4
gpt4 key购买 nike

我是 Java 编程的新手,所以请原谅我的愚蠢错误。我的问题是我的代码没有给出我想要的输出,即在彼此下方显示数组的所有偶数值,然后在彼此下方显示数组的所有不均匀值。这是我的代码:

//main class
public class Even_number_array
{

public static void main(String[] args)
{

array_class obj = new array_class();
obj.set_numbers();
}
}

//another class
public class array_class
{

private int arr[] =
{
10, 20, 7, 8, 3, 6, 11, 9, 7, 45
};

public void set_numbers()
{

for (int i = 0; i <= arr.length; i++)
{

if (arr[i] % 2 == 0)
{
System.out.println("These even numbers were found in the array:");
do
{
System.out.println(arr[i]);
i++;
}
while (arr[i] % 2 == 0);
}
else if (arr[i] % 2 != 0)
{
System.out.println("uneven numbers found in array:");
do
{
System.out.println(arr[i]);
i++;
}
while (arr[i] % 2 != 0);
}

}

}
}

这是我的输出(使用 Netbeans IDE,它显示了我遇到的错误,我已经包含了这些错误,因为我不太明白它的意思。):

These even numbers were found in the array:

10

20

These even numbers were found in the array:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

8

These even numbers were found in the array:

6

uneven numbers found in array:

9

7

45

at even_number_array.array_class.set_numbers(array_class.java:35)

at even_number_array.Even_number_array.main(Even_number_array.java:12)

Java Result: 1

我有几个问题,为什么我的数组中的数字 8 不与 10 和 20 一起打印,而 6 像 8 一样单独打印?而且,有没有一种方法可以使用数组的 Scanner 类获取用户输入,我将如何去做呢?

欢迎任何帮助!提前致谢:)

最佳答案

For 循环应该是 < 而不是 <=。

System.out.println("Even Numbers");
for (int i=0; i < arr.length;i++){
if((arr[i] % 2) == 0)
{
System.out.println(arr[i]);
}
}
System.out.println("Odd Numbers");
for (int i=0; i < arr.length;i++){
if((arr[i] % 2) != 0)
{
System.out.println(arr[i]);
}
}

ArrayList<Integer> array = new ArrayList<Integer>();
int[] intArray;
Scanner scanner = new Scanner(System.in);
int a = 0;
while(a != -1)
{
System.out.println("Please enter an integer -1 to quit: ");
a = scanner.nextInt();
if(a != -1)
{
array.add(a);
}
}
intArray = new int[array.size()];
for(int i = 0; i < array.size(); i++)
{
intArray[i] = array.get(i);
}
for(int b = 0; b < intArray.length; b++)
{
System.out.println("Integer" + b + ": " + intArray[b]);
}

将此代码放入您的主要方法中并执行。我希望这可以帮助您解决问题。

关于java - 数组和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789930/

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