gpt4 book ai didi

java - Java 中的入队、出队和 ViewQueue

转载 作者:搜寻专家 更新时间:2023-11-01 01:27:03 27 4
gpt4 key购买 nike

我正在用 java 做一个队列。这是我的代码:

public class ListQueue {
public static void main(String[] args){
Queue myQueue;
Scanner sc = new Scanner(System.in);
String input;
int choice = 99;
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,Empty?");
System.out.println("4,Count?");
System.out.println("5,View Queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
System.out.println("Please enter name: ");
input = sc.next();
myQueue.enqueue(input);
System.out.println(input + "is successful queued");
break;
case 2:
if(myQueue.isEmpty()){

}
break;
case 3:
if(myQueue.isEmpty()){
System.out.println("Queue is empty");
}else{
System.out.println("Queue is not empty");
}
break;
case 4:
System.out.println("Number of people is " + "the queue" + myQueue.size());
break;
case 5:
if(!myQueue.isEmpty())
myQueue.viewQueue();
else
System.out.println("Queue is empty");
break;
case 0:
System.out.println("Good-bye");
break;
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}

但是,我在 enqueue() 和 viewQueue() 中出错,我想知道为什么。我是否以错误的方式声明队列?提前致谢。我刚开始排队,所以请多多包涵。

最佳答案

Java 队列没有入队和出队方法,这些操作是使用以下方法完成的:

排队:

  • add(e):插入对象失败抛出异常
  • offer(e):如果插入对象失败则返回false

出队:

  • remove():如果队列为空则抛出异常
  • poll():如果队列为空则返回null

查看队列中的第一个对象:

  • element():如果队列为空则抛出异常
  • peek():如果队列为空则返回null

The add method, which Queue inherits from Collection, inserts an element unless it would violate the queue's capacity restrictions, in which case it throws IllegalStateException. The offer method, which is intended solely for use on bounded queues, differs from add only in that it indicates failure to insert an element by returning false.

(参见:http://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html)

你也可以检查这个,因为这更有用:

http://docs.oracle.com/cd/B10500_01/appdev.920/a96587/apexampl.htm

关于java - Java 中的入队、出队和 ViewQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17548150/

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