0
我想看看如何獲取客戶對象的名稱和食物,當它已被添加到隊列?所以說,我想打印一個字符串,使用第一個客戶對象的名稱和食物元素添加到隊列後?隊列窺視方法是佔位符,因爲我不確定如何在將隊列添加到隊列中後訪問對象的名稱和食物。訪問對象的對象變量?
結果會是這樣的:
「你想要什麼工藝做?!披薩或沙拉
沙拉
詹姆斯的沙拉做」
代碼:
主要類:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File customerTxt = new File("customer.txt");
Queue<Customer> pizza = new LinkedList<Customer>();
Queue<Customer> salad = new LinkedList<Customer>();
try {
Scanner readCus = new Scanner(customerTxt);
Scanner readFood = new Scanner(System.in);
while (readCus.hasNextLine()) {
String line = readCus.nextLine();
String[] strArray = line.split(",");
String customerName = strArray[0];
String customerFood = strArray[1];
Customer cus = new Customer(customerName, customerFood);
if (customerFood.equalsIgnoreCase("salad")) {
salad.add(cus);
}
if (customerFood.equalsIgnoreCase("pizza")) {
pizza.add(cus);
}
}
if (pizza.isEmpty() == false && salad.isEmpty() == false) {
System.out.println("What kind of food would you like to make?");
String foodChoice = readFood.nextLine();
if (foodChoice.equalsIgnoreCase("salad")) {
System.out.println(salad.peek());
}
if (foodChoice.equalsIgnoreCase("pizza")) {
System.out.println(salad.peek());
}
}
if (pizza.isEmpty() == true && salad.isEmpty() == false) {
System.out.println("There are no Pizzas left to process. I will just finish the rest of the Salads");
while (salad.isEmpty() == false) {
System.out.println(salad.peek());
}
}
if (pizza.isEmpty() == false && salad.isEmpty() == true) {
System.out.println("There are no Salads left to process. I will just finish the rest of the Pizzas");
while (pizza.isEmpty() == false) {
System.out.println(pizza.peek());
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Customer類:
public class Customer {
public String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String food = "";
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public Customer(String customerName, String customerFood) {
this.name = customerName;
this.food = customerFood;
}
}
是的,但你將如何訪問隊列來查看第一個隊列元素(這是一個客戶對象)並獲取它的食物和名稱變量?對不起,我可能沒有提出好的問題 –
'客戶c = pizza.remove()'會給你隊列頭上的元素。我建議你看一下Queue的java文檔。會幫助很多。 – ritratt