猿问

当第三个条目进入时,方法中的 for 循环被跳过。 JAVA

当我运行这段代码时,出于某种原因,当它遇到要添加到数组排序中的 test10 时,addListing 方法会忽略 for 循环并直接跳到底部。我很好奇,为什么for循环运行的test2.addListing(test);和test2.addListing(test9);而不是一前一后。


import java.util.Scanner;



public class TestListings {


public static void main(String[] args) {


StudentListings test = new StudentListings();

StudentListings test9 = new StudentListings();

StudentListings test10 = new StudentListings();

test.input();

test9.input();

test10.input();

Scanner sc = new Scanner(System.in);

int aSize = 0;

System.out.print("Enter Array Size: ");


aSize = Integer.parseInt(sc.nextLine());

ArraySort test2 = new ArraySort(aSize);

test2.addListing(test);

test2.addListing(test9);

test2.addListing(test10);


test2.showAllListings();




}

}

这是写的方法,第一次运行就运行,next = 0; 最初,但第三次(在 test10 中)它只是查看该行并跳过它。


人到中年有点甜
浏览 168回答 2
2回答

眼眸繁星

如果 next 第一次是 0 那么第三次是 2 并且 i 从 1 开始,所以条件 i <= 0 从一开始就是假的

倚天杖

我不是在解决这个问题,因为在我看来,您正在尝试(错综复杂地)做一些已经在 Java 中定义的事情。当您创建一个类,并且必须管理该类的对象数组时,Java 提供了一种非常简单的方法来做到这一点,我将逐步解释我将在您的位置上做什么:1 - 首先要做的是定义属于该类的对象之间的比较,您可以通过覆盖compareTo该类的方法来实现(该类必须实现Comparable <YourObject>);在你的情况下,我想它应该是这样的:public class StudentListings implements Comparable<StudentListings>{...@Overridepublic int compareTo(StudentListings element){&nbsp; &nbsp; return ...;&nbsp; &nbsp; }}您可以在其中定义一个StudentListing对象何时大于另一个对象。2 - 第二件事是ArrayList<StudentListings>在你的 中定义一个main,并初始化它:ArrayList<StudentListings> yourArray = new ArrayList<>();3 - 然后你必须将元素添加到该数组中(显然在你初始化它们之后):yourArray.add(test);yourArray.add(test9);yourArray.add(test10);4 - 现在你有你的数组,没有排序,要排序你只需要调用该方法Collections.sort(yourArray);现在您已经对 StudentListings 的 ArrayList 进行了排序。还有另一种方法可以实现这个结果,这里描述,我不太喜欢它,因为使用这种方法你必须在每次需要对数组进行排序时重新定义比较,并且因为你的main代码结果更复杂,但它有我解释的步骤的结果相同(因此,如果您必须以不同的方式对同一类对象的两个不同数组进行排序,例如一个按学生姓名,另一个按学生姓氏排序,则链接方法很有用)。
随时随地看视频慕课网APP

相关分类

Java
我要回答