我需要有关Java编程课程的帮助。我正在创建一个控制台花(商店)应用程序,该应用程序存储花的名称,颜色,年龄和价格。但是,我在打印创建用于存储添加的Flowers记录的LinkedList时遇到问题。我已经尝试了一段时间在Test类中使用showFlowers方法进行调整,但没有任何效果。感谢您的帮助,谢谢。这是我的代码。
花类
public class Flower {
//variables
private String name; //name of flower
private String colour; //colour of flower
private int age; //age of flower (days)
private double price; //price of flower
public Flower(String n, String c, int a, double p) {
this.name = n;
this.colour = c;
this.age = a;
this.price = p;
}
public void getName() {
System.out.println("Name: " + this.name);
}
public void getColour() {
System.out.println("Colour: " + this.colour);
}
public void getAge() {
System.out.println("Age (Days): " + this.age);
}
public void getPrice() {
System.out.println("Price: " + this.price);
}
public void getFullDetails(){
System.out.println("Name: " + this.name);
System.out.println("Colour: " + this.colour);
System.out.println("Age (Days): " + this.age);
System.out.println("Price: " + this.price);
}
}
FlowerTest类
package flower;
import java.util.LinkedList;
import java.util.Scanner;
public class FlowerTest {
private static LinkedList<Flower> myFlowers = new LinkedList();
public static void firstMenu() {
System.out.println("<------------ Welcome to the Flower Menu -------------->");
System.out.println("1. Add Flower Details");
System.out.println("2. Show All Flowers");
System.out.println("3. Exit");
System.out.println("Enter choice: ");
}
public static void mainMenu() {
for (;;) {
firstMenu();
Scanner inputScanner = new Scanner(System.in);
int choice = inputScanner.nextInt();
switch (choice) {
case 1:
createFlower(inputScanner);
break;
case 2:
showFlowers(inputScanner);
break;
case 3:
System.out.println("Goodbye");
System.exit(0);
break;
default:
//error handling
System.err.println("Unrecognized option");
break;
}
}
}
public static Flower createFlower(Scanner in) {
System.out.println("<-------- Adding Flower ---------->");
System.out.println("Input Flower Name: ");
String name = in.next();
System.out.println("Input Flower Colour: ");
String colour = in.next();
System.out.println("Input Flower Age (Days): ");
int age = in.nextInt();
System.out.println("Input Flower Price: ");
double price = in.nextDouble();
return new Flower(name, colour, age, price);
}
public static void showFlowers(Scanner in){
for (Flower flower : myFlowers) {
flower.getFullDetails();
}
}
public static void main(String[] args) {
mainMenu();
}
}
最佳答案
更改:
createFlower(inputScanner)
至:
myFlowers.add(createFlower(inputScanner));
关于java - 如何打印我的LinkedList中的条目?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54677223/