gpt4 book ai didi

java - 创建不确定数量的对象放入双端队列中

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:50 31 4
gpt4 key购买 nike

我正在尝试创建一个用户定义的双端队列来存储用户定义的数量对象。我创建一个 item 对象并为其指定值或 item# 和价格,然后将该对象存储在双端队列中。到目前为止,我的 Main 由一个单一的项目组成。每次我设置该项目时,它都会用最新的值覆盖以前存储的项目值。我怎样才能创建无限数量的项目来存储它们?

主要

import java.*;
import java.util.*;

public class MyDequeApp {

public static void main(String[] args)
{
//variables
String userinNum;
double userinPrice;
int queOp;

//creating new Item
Item item1= new Item();

//creating new Scanner
Scanner scan1=new Scanner(System.in);

//user input number of elements in the deque
System.out.println("Enter the number of elements in the que");
int queElm=scan1.nextInt();
MyDeque theQueue=new MyDeque(queElm);

//do/while so while user selects 1-7 they stay in the switch/case
do
{
//switch/case menu
System.out.println("1. Insert to front");
System.out.println("2. Insert to rear");
System.out.println("3. Remove from front");
System.out.println("4. Remove from rear");
System.out.println("5. Peek front");
System.out.println("6. Peek rear");
System.out.println("7. Display deque");
System.out.println("Anything else to Quit");

//user input the case number
queOp=scan1.nextInt();
scan1.nextLine();

switch(queOp)
{
//insert to front
case 1:
System.out.println("Enter an item number");
userinNum=scan1.nextLine();
item1.setNum(userinNum);
System.out.println("Enter a price");
userinPrice=scan1.nextDouble();
scan1.nextLine();
item1.setPrice(userinPrice);
System.out.println(item1.toString());
theQueue.insertFront(item1);
break;

//insert to rear
case 2:
System.out.println("Enter an item numbeR");
userinNum=scan1.nextLine();
item1.setNum(userinNum);
System.out.println("Enter a pricE");
userinPrice=scan1.nextDouble();
scan1.nextLine();
item1.setPrice(userinPrice);
System.out.println(item1.toString());
theQueue.insertFront(item1);
theQueue.insertRear(item1);
break;

//remove from front
case 3:
theQueue.removeFront();
break;

//remove from rear
case 4:
theQueue.removeRear();
break;

//peek front
case 5:
System.out.println(theQueue.peekFront());
break;

//peek rear
case 6:
System.out.println(theQueue.peekRear());
break;

//display the deque
case 7:
System.out.println(theQueue.toString());
break;

//quit
default:
break;


}

}while(queOp>0 && queOp<8);

}

}

最佳答案

您需要添加

item1= new Item(); 

要么在您完成一项并将其添加到队列中之后,要么在您为新一项输入数据之前的某个位置,否则程序会认为 item1 始终是同一项。

关于java - 创建不确定数量的对象放入双端队列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230402/

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