我想讓程式根據我的掃描儀輸入從 ArrayList 中進行選擇。就像,我寫早餐而不是甜食,它必須隨機化串列早餐甜食并列印隨機索引。
我仍在學習 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.
}
}
這是我已經寫過的課程:
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
}
我知道這很難理解,但英語不是我的主要語言,希望它可以理解。
uj5u.com熱心網友回復:
對我來說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將型別/風味組合在一起,或者您可以創建一個 POJO,其中包含與其直接關聯的型別/風味的資訊
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;
}
}
因此,這定義了預期的型別/口味,然后允許您定義特定型別/口味的膳食,并提供一種簡單的matches方法來確定它是否Meal屬于特定型別/口味,因為我很懶。
然后我們可以做一些像......
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");
}
}
查找隨機餐。
Now, because you should be running in Java 8 , you could also replace...
List<Meal> matchingMeals = new ArrayList<>(16);
for (Meal meal : meals) {
if (meal.matches(type, flavor)) {
matchingMeals.add(meal);
}
}
with...
Predicate<Meal> filter = meal -> meal.matches(type, flavor);
meals.stream().filter(filter).collect(Collectors.toList());
but that might be a bit of an ask
Map
Or, we can use a Map of some kind to link the List of data with a specific "key".
Since you have a "composite" key style (you strictly don't need to, but I like having the flavour and type separated), I started with a MealKey concept.
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;
}
}
The important thing here is to ensure that any instance of a key with the same type/flavor always returns the same hashCode
I then modified the POJO to make it simpler/easier to deal with...
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;
}
}
Then we fill our Map with the values we want
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);
And then we can look up the meals list based on the user input...
// 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");
}
}
注意:String如果你真的想要,你可以通過簡單地使用“型別” “值”來簡單地使用“鍵” ??
uj5u.com熱心網友回復:
我將依賴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) "?");
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369990.html
