1
我想創建一個用戶定義的雙向存儲用戶定義的金額對象。我創建一個項目對象,並給它的值或項目#和價格,而不是將對象存儲在雙端隊列中。到目前爲止,我的主要由一個單一的項目組成。每次我設置該項目時,都會將先前存儲的項目值寫入最近的項目中。我如何去創造一個數量不定的項目來存儲它們全部?創建不確定數量的對象來放入一個deque
主要
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);
}
}
我還是有點不清楚。你的意思是添加在申報item2,item3,第4項等?或與一個項目(變量)?你能詳細說明嗎? – Dan
或可能遞增? – Dan
只是它已經寫入代碼中了,但是您需要將該部分向下移動到循環中,以便循環也創建新項目。這裏令人困惑的部分是,item1實際上是每次循環中的不同項目,但在循環中本身具有相同的名稱,而在隊列中卻是不同的對象。 –