java中关于选择排序的运行时错误

我已经学会了选择排序,并且我尝试用java编写它。但它有一个错误,我认为这是一个运行时错误。我不知道要修复我的代码中的哪些内容。


这是代码:


import java.util.Scanner;


public class Main {


    public static void main(String args[])

    {


        int temp;


        Scanner sc=new Scanner(System.in);

        int number;

        int input=sc.nextInt();

        int [] carriage;

        carriage=new int[input];

        for(int i=0;i<input;i++)

        {

            number=sc.nextInt();

            carriage[i]=number;



        }

        int n=carriage.length;

        for(int i=0;i<n-1;i++)

        {

            for(int j=i+1;i<n;j++)

            {

                if(carriage[j]<carriage[i])

                {

                    temp=carriage[i];

                    carriage[i]=carriage[j];

                    carriage[j]=temp;

                }


            }

            System.out.println(carriage[i]+ " ");

        }

        sc.close();

    }

}


幕布斯7119047
浏览 66回答 1
1回答

慕的地6264312

我想你想对用户提供的整数进行排序。您的代码有 2 个错误。一个在以i开头的for循环中,条件应该是ipublic class Main {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; int temp;&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; int number;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter the number of integers to be sorted - ");&nbsp; &nbsp; &nbsp; &nbsp; int input = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; int[] carriage;&nbsp; &nbsp; &nbsp; &nbsp; carriage = new int[input];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < input; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter the "+ i+1 +"number&nbsp; - ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; number = sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; carriage[i] = number;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int n = carriage.length;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = i + 1; j < n; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (carriage[j] < carriage[i]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; temp = carriage[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; carriage[i] = carriage[j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; carriage[j] = temp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(carriage[i] + " ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sc.close();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java