gpt4 book ai didi

java - 访问对象的对象变量?

转载 作者:行者123 更新时间:2023-12-02 04:14:01 25 4
gpt4 key购买 nike

我想看看当客户对象名称和食物已经添加到队列中时,我将如何获取它?那么假设我想在将第一个客户对象添加到队列后使用其名称和食物元素打印一个字符串?队列查看方法是占位符,因为我不确定在将对象添加到队列后如何访问该对象的名称和食物。

结果将是这样的:

“您想加工什么:披萨还是沙拉?

沙拉

詹姆斯的沙拉做好了!”

代码:

主类:

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();
}
}
}

客户类别:

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;
}



}

最佳答案

您的类具有 getset 方法,用于访问类的属性。

很简单:

String food = cus.getFood(); //food now contains what is contained in the food variable of your cus object
cus.setName("Bob"); //The name of your customer is now Bob

将允许您获取/设置食物字符串和客户名称。

关于java - 访问对象的对象变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33508350/

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