如何根据用户输入选择一个 ArrayList?
How to choose an ArrayList based on user input?
我想让程序根据我的扫描仪输入从 ArrayList 中进行选择。
比如,我写早餐而不是甜蜜,它必须随机化列表 breakfastSweet 并打印随机索引。
我仍在学习 Java,我只是在玩弄并尝试编写小项目来训练它。
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// program begins here, you get asked what kind of lunch you want to eat
// after asking for the meal type and answering it, it goes to the next question
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
ArrayList<String> breakfastSweet = new ArrayList();
ArrayList<String> breakfastSavory = new ArrayList();
ArrayList<String> lunchSweet = new ArrayList();
ArrayList<String> lunchSavory = new ArrayList();
ArrayList<String> dinnerSweet = new ArrayList();
ArrayList<String> dinnerSavory = new ArrayList();
GetRandomFromList.outputMeal(mealType, flavor, dinnerSavory); // doesn't make sense to put the list already in, I want it to automatically select the right list.
}
}
这是我已经写的class:
import java.util.ArrayList;
import java.util.Random;
public class GetRandomFromList {
private static String randomList(ArrayList<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
public static void outputMeal(String mealType, String flavor, ArrayList<String> list){ // the list should be chosen automatically, so my code doesn't work as I want it to work
if (mealType.equals("breakfast") && flavor.equals("sweet")){
System.out.println("What about " + GetRandomFromList.randomList() + "?");
}
}
}
我能否以某种方式将列表存储在变量中,可能是这样的:
if (mealType.equals("breakfast") && flavor.equals("sweet")){
// here make a variable of the breakfastSweet list
}
我知道很难理解我,但英语不是我的主要语言,希望它能理解。
对我来说 GetRandomFromList
没有意义,除非 GetRandomFromList
包含所有数据,相反,只需将所选 List
的引用分配给另一个变量然后 shuffle
它得到一个随机值,例如...
// Previously created lists
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
ArrayList<String> userChoice = null;
if (mealType.equals("breakfast") && flavor.equals("sweet")) {
userChoice = breakfastSweet;
} else if {...}
if (userChoice != null) {
Collections.shuffle(userChoice, rand);
String value = userChoice.get(0);
}
与大多数事情一样,给这只猫剥皮的方法不止一种。例如,您可以 Map
将 type/flavors 组合在一起,或者您可以创建一个 POJO,其中包含有关它的信息 type/flavor 直接与之关联
POJO,带有 List
过滤器...
public class Meal {
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
private Type type;
private Flavor flavor;
private String description;
public Meal(Type type, Flavor flavor, String description) {
this.type = type;
this.flavor = flavor;
this.description = description;
}
public Type getType() {
return type;
}
public Flavor getFlavor() {
return flavor;
}
public String getDescription() {
return description;
}
public boolean matches(Type type, Flavor flavor) {
return getType() == type && getFlavor() == flavor;
}
}
因此,这定义了预期的 type/flavors,然后允许您定义特定 type/flavor 的一餐,并提供了一个简单的 matches
方法来确定 Meal
是特定的type/flavor,因为我很懒。
然后我们可以做类似...
List<Meal> meals = new ArrayList<>(16);
// Get user input
Meal.Type type = Meal.Type.forType(mealType.toUpperCase());
Meal.Flavor flavor = Meal.Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
Collections.shuffle(matchingMeals);
Meal meal = matchingMeals.get(0);
System.out.println(meal.getDescription());
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
查找随机餐。
现在,因为你应该是 Java 8+ 中的 运行,你也可以替换...
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
与...
Predicate<Meal> filter = meal -> meal.matches(type, flavor);
meals.stream().filter(filter).collect(Collectors.toList());
但这可能有点问题
Map
或者,我们可以使用某种 Map
来 link 具有特定“键”的数据 List
。
因为你有一个“复合”键样式(你完全不需要,但我喜欢将风格和类型分开),我从一个 MealKey
概念开始。
public class MealKey {
private Type type;
private Flavor flavor;
public MealKey(Type type, Flavor flavor) {
this.type = type;
this.flavor = flavor;
}
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.type);
hash = 97 * hash + Objects.hashCode(this.flavor);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MealKey other = (MealKey) obj;
if (this.type != other.type) {
return false;
}
if (this.flavor != other.flavor) {
return false;
}
return true;
}
}
这里重要的是确保具有相同 type/flavor 的任何实例始终 returns 相同 hashCode
然后我修改了 POJO 使其 simpler/easier 来处理...
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public class Meal {
private String description;
public Meal(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
然后我们用我们想要的值填充我们的Map
Map<MealKey, List<Meal>> meals = new HashMap<>();
// Fill the meals
List<Meal> breakfastSweet = new ArrayList<>();
// Add some meals to the list
meals.put(new MealKey(Type.BREAKFAST, Flavor.SWEET), breakfastSweet);
然后我们可以根据用户输入查找餐单...
// Get user input
Type type = Type.forType(mealType.toUpperCase());
Flavor flavor = Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
MealKey key = new MealKey(type, flavor);
List<Meal> mealsList = meals.get(key);
if (mealsList != null) {
Collections.shuffle(mealsList);
System.out.println(mealsList.get(0).getDescription());
}
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
nb:如果你真的想
我会依赖 Map
作为构建数据的方式:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
Map<String, Map<String, List<String>>> meals = new HashMap<>();
Map<String, List<String>> breakfast = new HashMap<>();
breakfast.put("sweet", new ArrayList<>());
meals.put("breakfast", breakfast);
// The same for the following:
// - lunch --> sweet --> list
// - lunch --> savory --> list
// - dinner --> sweet --> list
// - dinner --> savory --> list
GetRandomFromList.outputMeal(mealType, flavor, meals);
}
}
然后你的 GetRandomFromList
会更简单:
public class GetRandomFromList {
private static String randomList(List<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
public static void outputMeal(String mealType, String flavor, Map<String, Map<String, List<String>>> meals){
Map<String, List<String>> meal = meals.get(mealType);
if (meal.isEmpty()) {
System.out.println("No possibilities found");
} else {
List<String> mealFlavourPossibilities = meal.get(flavor);
if (mealFlavourPossibilities.isEmpty()) {
System.out.println("No possibilities found");
} else {
System.out.println("What about " + GetRandomFromList.randomList(mealFlavourPossibilities) + "?");
}
}
}
}
我想让程序根据我的扫描仪输入从 ArrayList 中进行选择。 比如,我写早餐而不是甜蜜,它必须随机化列表 breakfastSweet 并打印随机索引。
我仍在学习 Java,我只是在玩弄并尝试编写小项目来训练它。
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// program begins here, you get asked what kind of lunch you want to eat
// after asking for the meal type and answering it, it goes to the next question
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
ArrayList<String> breakfastSweet = new ArrayList();
ArrayList<String> breakfastSavory = new ArrayList();
ArrayList<String> lunchSweet = new ArrayList();
ArrayList<String> lunchSavory = new ArrayList();
ArrayList<String> dinnerSweet = new ArrayList();
ArrayList<String> dinnerSavory = new ArrayList();
GetRandomFromList.outputMeal(mealType, flavor, dinnerSavory); // doesn't make sense to put the list already in, I want it to automatically select the right list.
}
}
这是我已经写的class:
import java.util.ArrayList;
import java.util.Random;
public class GetRandomFromList {
private static String randomList(ArrayList<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
public static void outputMeal(String mealType, String flavor, ArrayList<String> list){ // the list should be chosen automatically, so my code doesn't work as I want it to work
if (mealType.equals("breakfast") && flavor.equals("sweet")){
System.out.println("What about " + GetRandomFromList.randomList() + "?");
}
}
}
我能否以某种方式将列表存储在变量中,可能是这样的:
if (mealType.equals("breakfast") && flavor.equals("sweet")){
// here make a variable of the breakfastSweet list
}
我知道很难理解我,但英语不是我的主要语言,希望它能理解。
对我来说 GetRandomFromList
没有意义,除非 GetRandomFromList
包含所有数据,相反,只需将所选 List
的引用分配给另一个变量然后 shuffle
它得到一个随机值,例如...
// Previously created lists
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
ArrayList<String> userChoice = null;
if (mealType.equals("breakfast") && flavor.equals("sweet")) {
userChoice = breakfastSweet;
} else if {...}
if (userChoice != null) {
Collections.shuffle(userChoice, rand);
String value = userChoice.get(0);
}
与大多数事情一样,给这只猫剥皮的方法不止一种。例如,您可以 Map
将 type/flavors 组合在一起,或者您可以创建一个 POJO,其中包含有关它的信息 type/flavor 直接与之关联
POJO,带有 List
过滤器...
public class Meal {
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
private Type type;
private Flavor flavor;
private String description;
public Meal(Type type, Flavor flavor, String description) {
this.type = type;
this.flavor = flavor;
this.description = description;
}
public Type getType() {
return type;
}
public Flavor getFlavor() {
return flavor;
}
public String getDescription() {
return description;
}
public boolean matches(Type type, Flavor flavor) {
return getType() == type && getFlavor() == flavor;
}
}
因此,这定义了预期的 type/flavors,然后允许您定义特定 type/flavor 的一餐,并提供了一个简单的 matches
方法来确定 Meal
是特定的type/flavor,因为我很懒。
然后我们可以做类似...
List<Meal> meals = new ArrayList<>(16);
// Get user input
Meal.Type type = Meal.Type.forType(mealType.toUpperCase());
Meal.Flavor flavor = Meal.Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
Collections.shuffle(matchingMeals);
Meal meal = matchingMeals.get(0);
System.out.println(meal.getDescription());
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
查找随机餐。
现在,因为你应该是 Java 8+ 中的 运行,你也可以替换...
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
与...
Predicate<Meal> filter = meal -> meal.matches(type, flavor);
meals.stream().filter(filter).collect(Collectors.toList());
但这可能有点问题
Map
或者,我们可以使用某种 Map
来 link 具有特定“键”的数据 List
。
因为你有一个“复合”键样式(你完全不需要,但我喜欢将风格和类型分开),我从一个 MealKey
概念开始。
public class MealKey {
private Type type;
private Flavor flavor;
public MealKey(Type type, Flavor flavor) {
this.type = type;
this.flavor = flavor;
}
@Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + Objects.hashCode(this.type);
hash = 97 * hash + Objects.hashCode(this.flavor);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MealKey other = (MealKey) obj;
if (this.type != other.type) {
return false;
}
if (this.flavor != other.flavor) {
return false;
}
return true;
}
}
这里重要的是确保具有相同 type/flavor 的任何实例始终 returns 相同 hashCode
然后我修改了 POJO 使其 simpler/easier 来处理...
public enum Type {
BREAKFAST, LUNCH, DINNER;
public static Type forType(String value) {
try {
return Type.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public enum Flavor {
SWEET, SAVORY;
public static Flavor forFlavor(String value) {
try {
return Flavor.valueOf(value.toUpperCase());
} catch (IllegalArgumentException exp) {
return null;
}
}
}
public class Meal {
private String description;
public Meal(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
然后我们用我们想要的值填充我们的Map
Map<MealKey, List<Meal>> meals = new HashMap<>();
// Fill the meals
List<Meal> breakfastSweet = new ArrayList<>();
// Add some meals to the list
meals.put(new MealKey(Type.BREAKFAST, Flavor.SWEET), breakfastSweet);
然后我们可以根据用户输入查找餐单...
// Get user input
Type type = Type.forType(mealType.toUpperCase());
Flavor flavor = Flavor.forFlavor(flavorValue.toUpperCase());
if (type != null && flavor != null) {
MealKey key = new MealKey(type, flavor);
List<Meal> mealsList = meals.get(key);
if (mealsList != null) {
Collections.shuffle(mealsList);
System.out.println(mealsList.get(0).getDescription());
}
} else {
if (type == null) {
System.out.println(mealType + " is not a valid type");
}
if (flavor == null) {
System.out.println(flavorValue + " is not a valid flavor");
}
}
nb:如果你真的想
我会依赖 Map
作为构建数据的方式:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi, welcome to Recipe-Randomizer! What kind of meal do you want, breakfast, lunch or maybe dinner?");
System.out.print("Type one of the give choices now: ");
String mealType = scanner.nextLine();
System.out.print("So you want to eat for " + mealType + ". Do you want to eat some sweet or savory " + mealType + "?\nType in one of the given choices: ");
String flavor = scanner.nextLine();
System.out.println("A " + flavor + " " + mealType + "? Well, let's see what we have here.\nI am going to pick a random recipe.\nPlease wait...");
// list of meals, list name describes
Map<String, Map<String, List<String>>> meals = new HashMap<>();
Map<String, List<String>> breakfast = new HashMap<>();
breakfast.put("sweet", new ArrayList<>());
meals.put("breakfast", breakfast);
// The same for the following:
// - lunch --> sweet --> list
// - lunch --> savory --> list
// - dinner --> sweet --> list
// - dinner --> savory --> list
GetRandomFromList.outputMeal(mealType, flavor, meals);
}
}
然后你的 GetRandomFromList
会更简单:
public class GetRandomFromList {
private static String randomList(List<String> list) {
Random rand = new Random();
return list.get(rand.nextInt(list.size()));
}
public static void outputMeal(String mealType, String flavor, Map<String, Map<String, List<String>>> meals){
Map<String, List<String>> meal = meals.get(mealType);
if (meal.isEmpty()) {
System.out.println("No possibilities found");
} else {
List<String> mealFlavourPossibilities = meal.get(flavor);
if (mealFlavourPossibilities.isEmpty()) {
System.out.println("No possibilities found");
} else {
System.out.println("What about " + GetRandomFromList.randomList(mealFlavourPossibilities) + "?");
}
}
}
}