如何创建一个既可以保存字符串又可以保存整数的队列数组?

wvt8vs2t  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(452)

我必须创建一个数组来保存一个用户输入,这个用户输入是3个字母的代码,后跟一个票证号。例如,ama-34。我该怎么做?我知道long是不正确的,我只是从另一个项目建模。我还必须考虑到用户的输入和操作,我有一个艰难的时间。这就是我目前所拥有的。。。

class QueueOrder{

    //Global Variables
    static Scanner orderScan = new Scanner(System.in);

    //Variables
    public int MaxSize;
    //How to make an array hold both names and numbers??
    public long[] BodaciousArray; 
    public int Front;  //Track the front pointer
    public int Rear;   //track the last pointer 
    public int NumberOfOrders; //track the number of orders in the system

    //Constructor
    public QueueOrder(int size){

        MaxSize = size;
        BodaciousArray = new long[MaxSize];
        Front = 0;
        Rear = -1;
        NumberOfOrders = 0;
    }

    //Enqueue - add to the rear of the queue
    //Allow the server to add one to the array
    public void Enqueue(){
        long j = 0;
        //Add a wrap around
        if(Rear == MaxSize - 1){           
            Rear = -1;
        }
        //Increment the rear and insert a new item
        BodaciousArray[++Rear] = j;
        NumberOfOrders++;
    }

    //Dequeue - remove one from the array
    //Allow the server to remove what is next in line
    public long Dequeue(){
        //Get the first value and incrament the front
        long temp = BodaciousArray[Front++];
        //Add a wrap around
        if(Front == MaxSize){
            Front = 0;
        }
        //Remove one item
        NumberOfOrders--;
        return temp;                
    }

    //Peek at the front of the queue
    //Allow the server to see what order is next
    public long peekFront(){
        return BodaciousArray[Front];
    }

    //Check to is the queue is empty
    public boolean isEmpty(){
        return(NumberOfOrders == 0);
    }

    //Check to see if the queue is full
    public boolean isFull(){
        return(NumberOfOrders == MaxSize);
    }

    //Check how many items are in the queue
    public int size(){
        return NumberOfOrders;
    }

    public void DisplayQueueOrder(){
        int i;
        if(Front == Rear){
            System.out.println("There are no orders to fill");
        }else{
            for(i = Front; i < Rear; i++){
                System.out.print("The current orders are: " 
                        + BodaciousArray[i] + ", ");
            }
        }
    }
oo7oh9g9

oo7oh9g91#

如果您想保持这两个独立,并且3个字母的代码是唯一的,hashmap是一种方法:

HashMap<String, Integer> queueArray = new HashMap<String, Integer>();
queueArray.put("Ama", 34);
System.out.println(arr.get("Ama"));

输出:

34

否则,为什么不这样做:

String[] tickets = {"Ama-34", "Abc-60", "Xyz-76"};

public String getTicketCode(int index) {
    return tickets[index].split("-")[0];
}

public int getTicketNumber(int index) {
    return Integer.parseInt(tickets[index].split("-")[1]);
}

用法如下:

System.out.println(getTicketCode(0));
System.out.println(getTicketNumber(0));

印刷品:

Ama
76

相关问题