gpt4 book ai didi

java - 创建数组时需要 吗?

转载 作者:行者123 更新时间:2023-11-30 03:48:34 25 4
gpt4 key购买 nike

我正在编写一个航空公司程序,允许用户输入经济舱、商务舱和头等舱每个座位区的名称和餐食选择。我试图将所有姓名和餐食保存到一个数组中。但我收到语法错误。

当我实现传单数组时,我收到了预期的消息。

我看过堆栈溢出。据我所知,以这种方式初始化我的数组应该可以。

感谢您的帮助。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Flyers
{
public Flyers()
{

}

public List<String> seat = new ArrayList<>();
int numberOfFlyers;
int numberOfMeals;
String name;
String meal;

String[][] flyer;

public void addEconomyFlyer()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
numberOfFlyers = in.nextInt();

flyer = new [numberOfFlyers][numberOfFlyers];
}
}

最佳答案

I want each [][] to have the same number of items that is equal to the number of people on the plane. Then I will add a nested for loop that will add a name for each of the flyers, and a meal choice. ultimately i need to be able to print out the array Name and their Meal choice.

几乎,这里的问题是您没有指定数组的类型。

flyer = new [numberOfFlyers][numberOfFlyers];

应该是

flyer = new String[numberOfFlyers][numberOfFlyers];

但是这没有多大意义。一种解决方案是使用,

flyer = new String[numberOfFlyers][2];

其中 0 是姓名,1 是餐食。但是,实际上您应该有一张 POJO 传单,

flyer = new Flyer[numberOfFlyers];

Flyer 可能看起来像这样,

class Flyer {
Flyer(String name, String mealType) {
this.name = name;
this.mealType = mealType;
}
String name;
String mealType;
public String toString() {
return "Name: " + name + ", Meal: " + mealType;
}
}

然后您可以创建新的 Flyer 并在循环中调用 toString()。您还可以选择为 namemealType 添加 getter 和 setter 函数。

关于java - 创建数组时需要 <identifier> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24968171/

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