gpt4 book ai didi

java - 如何让用户选择任何电影

转载 作者:行者123 更新时间:2023-12-01 13:05:18 25 4
gpt4 key购买 nike

我的程序是关于用户从列出的 7 部电影中选择一部电影或许多人想要观看的电影以及显示的价格。该程序将为用户提供 7 部电影可供选择,如果他们想选择另一部电影,价格将加到总数中。到目前为止,我有一系列电影和价格,但我不确定应该如何为电影做出用户选择并添加总价格。我应该使用 switch 语句还是循环我很困惑。这是我到目前为止所拥有的:

import java.util.Scanner;
public class MovieHits {

public static void main(String[] args)
{
//Declare Variables
Scanner keyboard = new Scanner(System.in);
int userChoice = 0;
String [] Movie = new String [7];

int [] movieCost ={ 5, 4, 3, 6, 4, 4, 3};

Movie [0] = "Iron Man";
Movie [1] = "Transformers";
Movie [2] = "Godzilla";
Movie [3] = "Fast and Furious";
Movie [4] = "Captain America";
Movie [5] = "X Men";
Movie [6] = "Rio";

//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");

//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
for ( int index = 0; index < 7; index = index + 1 )
{
System.out.println(Movie[index]);
System.out.println("\t" + "Price: $" + movieCost[index]);
}

//Switch Statement to give user a menu to choose a movie
switch (userChoice)
{
case 1:
System.out.println("The movie you have chosen.");
break;

最佳答案

您应该使用循环来打印电影选择。读取用户输入后,您可以使用 switch case 来确定选择了哪部电影。您的示例代码实际上并不读取用户输入,实例化的 Scanner 对象从未被使用。在开关盒之前,您应该有例如

userChoice = keyboard.nextInt();

但是,有一种更面向对象的“Java 方式”可以使用 Map 而不是 String 数组来完成此操作,并且无需使用 switch-case:

public class MovieHits {
public static class Movie {
private int cost;
private String name;

public Movie(String name, int cost) {
this.cost = cost;
this.name = name;
}

public int getCost() {
return cost;
}

public String getName() {
return name;
}
}

public static void main(String[] args) {

//Declare Variables
Scanner keyboard = new Scanner(System.in);
int userChoice;
Map<Integer, Movie> movies = new HashMap<Integer, Movie>();
movies.put(1, new Movie("Iron Man", 5));
movies.put(2, new Movie("Transformers", 4));
movies.put(3, new Movie("Godzilla", 3));
// ...

//Welcome the user
System.out.println("Hello, Welcome to TC Movies OnDemand.");

//Display the listed movies so the user can know with movie they want to watch
System.out.println("\nChoose which movie you want to watch: ");
Set<Integer> keys = movies.keySet();
for (Integer key : keys) {
Movie movie = movies.get(key);
System.out.println(key + ": " + movie.getName());
System.out.println("\t" + "Price: $" + movie.getCost());
}
userChoice = keyboard.nextInt();
System.out.println("You have chosen " + movies.get(userChoice).getName());

内部类通常违背最佳实践,但在本例中我使用它来保持简单。

如果用户可以选择多个电影,则在 while 循环中读取 userChoice 并用特定数字或用户输入空行来中断它。在循环内存储选定的电影,例如在列表中,计算用户在循环内或选择所有想要的电影后观看的总价格。

关于java - 如何让用户选择任何电影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308253/

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