Java对象[]排序

Java对象[]排序,java,sorting,comparable,Java,Sorting,Comparable,我试图在每次添加对象时对创建的对象数组进行排序。我编写了一个compareTo方法,它打印出每一行,但在我尝试排序时抛出一个异常。我正在初始化一个包含99个元素(maxLen)的元素[],然后使用topIndex作为计数器来查找“实际”长度。扫描仪用于获取用户输入以创建元素。编辑——我添加了完整的代码 import java.util.Arrays; import java.util.Scanner; public class mainmenu { static Element[] dat

我试图在每次添加对象时对创建的对象数组进行排序。我编写了一个compareTo方法,它打印出每一行,但在我尝试排序时抛出一个异常。我正在初始化一个包含99个元素(maxLen)的元素[],然后使用topIndex作为计数器来查找“实际”长度。扫描仪用于获取用户输入以创建元素。编辑——我添加了完整的代码

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



public class mainmenu {
static Element[] data = new Element[100];
static int maxLen= 99; 
static int topIndex= -1;
@SuppressWarnings("rawtypes")


public static void main(String[] args){


    menu();


}


public static void menu(){
    boolean leave = true;
    Scanner in = new Scanner(System.in);
    while(leave){
        //loop. unless value is 1-7, keeps recycling    
        System.out.println("Please select a menu option: ");
        System.out.println("'1'- enque ");
        System.out.println("'2'- deque");
        System.out.println("'3'- peek");
        System.out.println("'4'- display");
        System.out.println("'5' empty queue");
        System.out.println("'6'- check if the queue is empty");
        System.out.println("'7' to exit the program");
        String select = in.next();
        if ((select.equals("1") || select.equals("2")|| select.equals("3")|| select.equals("4")|| 
                select.equals("5")|| select.equals("6")|| select.equals("7")))
            leave = callMethods(select );
        else{
            System.out.println("Please enter a valid menu option.");
        }
    }
}

public static  boolean callMethods(String select )
{
    boolean leave= true;
    int sel = Integer.parseInt(select);

    switch(sel){
    case 1:

        enqueue();

        break;
    case 2:
        dequeue();
        break;
    case 3:
        peek();

        break;
    case 4:
        display();

        break;
    case 5:
        empty();

        break;
    case 6:
        if( isEmpty()){
            System.out.println("The structure is empty");
        }
        else{
            System.out.println("The structure is not empty.");
        }
        break;
    case 7:
        System.out.println("Bye!");
        leave = false;
    }
    return leave;
}

public static void enqueue(){
    boolean isInt = false;
    String st = null;
    int index = 0;
    Scanner in = new Scanner(System.in);

    while(!isInt){  //loop continues until input is an integer type
        System.out.println("Please enter a priority level for this element");
        st = in.next();
        if (isInteger(st) == true){// calls method to check if value is integer
            index = Integer.parseInt(st);//parses the string into a integer
            isInt = true;
        }
        else //if value isnt integer, try again
            System.out.println("Invalid Input.");
    }
    System.out.println("Please enter the string of information.");
    String info = in.next();

    Element e = new Element(info, index);

    if (topIndex == maxLen){
        System.out.println("Data Structure is full.");
    }
    else if (isEmpty()){
        data[0] = e;
        topIndex++;
    }
    else {
        topIndex++;
        data[topIndex]=e;
        System.out.println("Added "+ e.getPriority() + " at "+ e.getInfo());
        System.out.println(topIndex);

        Arrays.sort(data);

    }

}

private static boolean isInteger(String s) {
    //checks to see if string can be parsed as an integer.


    try{
        Integer.parseInt(s);
        return true;
    }
    catch( Exception e ){
        return false;
    }


}
public static void dequeue(){
    if(isEmpty()){
        System.out.println("The structure is empty.");
    }
    else{
        Element e = data[topIndex];
        System.out.println("Removing Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
        --topIndex;
    }
}

public static void peek(){
    if (isEmpty()){
        System.out.println("The structure is empty.");

    }
    else {
        Element e = (data[0]);
        System.out.println("Element: " +  e.getInfo()+ " Priority Level: " + e.getPriority());
    }
}

public static void display(){
    System.out.println("topIndex " + topIndex);
    if (topIndex==-1){
        System.out.println("The structure is empty.");

    }
    else {
        for(int i = 0; i <= topIndex; i++){
            System.out.println("Index: " +i);
            Element e = data[i];
            System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());

        }
    }
}

public static void empty(){
    System.out.println("Erasing data.");
    topIndex=-1;
}

public static boolean isEmpty(){
    return (topIndex==-1);
}
导入java.util.array;
导入java.util.Scanner;
公共类主菜单{
静态元素[]数据=新元素[100];
静态整数maxLen=99;
静态int topIndex=-1;
@抑制警告(“原始类型”)
公共静态void main(字符串[]args){
菜单();
}
公共静态无效菜单(){
布尔左=真;
扫描仪输入=新扫描仪(系统输入);
当(离开){
//循环。除非值为1-7,否则保持循环
System.out.println(“请选择一个菜单选项:”);
System.out.println(“'1'-enque”);
System.out.println(“'2'-deque”);
System.out.println(“'3'-peek”);
System.out.println(“'4'-显示”);
System.out.println(“'5'空队列”);
System.out.println(“'6'-检查队列是否为空”);
System.out.println(“'7'退出程序”);
字符串select=in.next();
如果((select.equals(“1”)| select.equals(“2”)| select.equals(“3”)| select.equals(“4”)|
select.equals(“5”)| select.equals(“6”)| select.equals(“7”))
离开=调用方法(选择);
否则{
System.out.println(“请输入有效的菜单选项”);
}
}
}
公共静态布尔调用方法(字符串选择)
{
布尔左=真;
int sel=Integer.parseInt(选择);
开关(sel){
案例1:
排队();
打破
案例2:
出列();
打破
案例3:
peek();
打破
案例4:
显示();
打破
案例5:
空();
打破
案例6:
if(isEmpty()){
System.out.println(“结构为空”);
}
否则{
System.out.println(“结构不是空的。”);
}
打破
案例7:
System.out.println(“再见!”);
离开=假;
}
回程假;
}
公共静态void队列(){
布尔isInt=false;
字符串st=null;
int指数=0;
扫描仪输入=新扫描仪(系统输入);
而(!isInt){//循环将继续,直到输入为整数类型
System.out.println(“请输入此元素的优先级”);
st=in.next();
if(isInteger(st)==true){//调用方法检查值是否为整数
index=Integer.parseInt(st);//将字符串解析为整数
isInt=真;
}
else//如果值不是整数,请重试
System.out.println(“无效输入”);
}
System.out.println(“请输入信息字符串”);
String info=in.next();
元素e=新元素(信息、索引);
如果(topIndex==maxLen){
System.out.println(“数据结构已满”);
}
else if(isEmpty()){
数据[0]=e;
topIndex++;
}
否则{
topIndex++;
数据[topIndex]=e;
System.out.println(“在“+e.getInfo()”处添加“+e.getPriority()+”);
系统输出打印项次(topIndex);
数组。排序(数据);
}
}
私有静态布尔isInteger(字符串s){
//检查字符串是否可以解析为整数。
试一试{
整数.parseInt(s);
返回true;
}
捕获(例外e){
返回false;
}
}
公共静态无效出列(){
if(isEmpty()){
System.out.println(“结构为空”);
}
否则{
元素e=数据[topIndex];
System.out.println(“删除元素:+e.getInfo()+”优先级:+e.getPriority());
--topIndex;
}
}
公共静态void peek(){
if(isEmpty()){
System.out.println(“结构为空”);
}
否则{
元素e=(数据[0]);
System.out.println(“元素:+e.getInfo()+”优先级:+e.getPriority());
}
}
公共静态无效显示(){
System.out.println(“topIndex”+topIndex);
如果(topIndex==-1){
System.out.println(“结构为空”);
}
否则{

对于(int i=0;i您已将
元素[]
数组
数据
指定给
数组.sort()
方法,该方法的大小
100
,但数据数组的所有元素都未初始化。因此,调用
e.getPriority()
将导致
空点异常
因为
e
null
。首先初始化
数据
数组的所有元素

for(int i=0 ; i< data.length; i++)
   e = new Element(info, index); // replace with relevant info and index of your contest

您已将
Element[]
array
data
指定给
array.sort()
方法,该方法的大小为
100
,但数据数组的所有元素都未初始化。因此,调用例如
e.getPriority()
将导致
空点异常
因为
e
null
。首先初始化
数据
数组的所有元素

for(int i=0 ; i< data.length; i++)
   e = new Element(info, index); // replace with relevant info and index of your contest

进行比较时,您要确定一个对象的排名是否比另一个对象高出任意条件

我注意到,您没有检查您要比较的对象是否为
null
——您应该这样做

public int compareTo(Element e) {
    if(e == null) {
        return this.index;
    } else {
        // rest of your logic goes here
    }
}

进行比较时,您要确定一个对象的排名是否比另一个对象高出任意条件

我注意到,您没有检查您要比较的对象是否为
null
——您应该这样做

public int compareTo(Element e) {
    if(e == null) {
        return this.index;
    } else {
        // rest of your logic goes here
    }
}

Arrays.sort
要求所有数组元素都是非空的。您只想对非空部分进行排序,因此将
array.sort(data)
替换为
Arrays.sort(data,0,topIndex+1)

不要像其他人建议的那样修改
compareTo
以允许空参数,因为
Comparable
的契约规定您的实现应该
if (!(e instanceof Element))
    throw new ClassCastException("An Element object expected.");