gpt4 book ai didi

java - 尝试运行鸡尾酒代码 java 时出现越界异常

转载 作者:行者123 更新时间:2023-12-02 10:10:55 24 4
gpt4 key购买 nike

我正在尝试进行鸡尾酒排序,但我在 if (a[i] > a[i + 1]) 行遇到了越界异常。我不确定为什么。

这是完整的代码。抱歉,如果这是完全错误的。

import java.util.Arrays;
import java.util.Scanner;

public class Cocktail
{

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println(a[0]);
while (switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println(count);
}
}

}

}

最佳答案

你需要改变

if (a[i] > a[i + 1])像这样 --> if (i < a.length-1 && a[i] > a[i + 1]) .

问题是它正在尝试到达第 11 个元素;)

如果可以的话,这是您的代码的编辑版本:

Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;


int[]a = new int[10];
System.out.println("enter 10 Integers: ");// # Added to make code clearer
for (int i = 0; i < a.length; i++)
{

int value = input.nextInt();
a[i] = value;
}
System.out.println("thankyou, Sorting now!");//# also this one
while(switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) // <-- # here was the problem
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) //<-- # Also Here
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println("count is "+ count);
}
}
// # added part to print array for testing
System.out.println("Sorted Array:");
for (int i = 0; i <a.length ; i++) {


System.out.print(a[i]+", ");
}


}//main

}//class

这是输出:

OUTPUT

复制并粘贴它,运行并快乐编码=D

关于java - 尝试运行鸡尾酒代码 java 时出现越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55009205/

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