gpt4 book ai didi

java - 线程中的异常 “main” java.lang.ArrayIndexOutOfBoundsException : 5 ERROR

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

我需要打印具有重复数字(例如 11 或 121)的数字。但是,当我输入像 22 这样的输入时,它会出错。 。我不明白为什么会收到错误消息。知道如何修复此错误吗?

import java.util.Scanner;

public class IdenticalNumbers {

public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

int max = 0;
int[] arr = new int[5];
int count =0;

// Check if an int value is available
while (sc.hasNextInt())
{
// Read an int value
int num = sc.nextInt();

while (IsRepeating(num)){
arr[count] = num;
count += 1;
}

if (num > max){
max = num;
}


}
System.out.println("Maximum integer is: " + max);
System.out.println("Numbers with identical digits are: ");
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
sc.close();
}

public static boolean IsRepeating(int number)
{
String textual = "" + number;
for (int i = 0; i < textual.length(); i++)
{
for (int j = i + 1; j < textual.length(); j++)
{
if (textual.charAt(i) == textual.charAt(j))
return true;
}
}

return false;
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at IdenticalNumbers.main(IdenticalNumbers.java:23)

最佳答案

原因在于这一行while (IsRepeating(num)){。在循环内,您不会更改 num,因此如果它是重复的,它将始终如此。此行在 num 重复时循环(并增加 count),即永远。

您应该将其更改为 if (IsRepeating(num)){

关于java - 线程中的异常 “main” java.lang.ArrayIndexOutOfBoundsException : 5 ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291365/

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