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

时间:2014-04-26 07:54:30

标签: java arrays loops

我的节目是关于用户选择电影或许多人想要从列出的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;

1 个答案:

答案 0 :(得分:1)

您应该使用循环打印出电影选择。阅读用户输入后,您可以使用开关盒确定选择了哪部电影。 您的示例代码实际上不读取用户输入,从不使用实例化的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并使用特定数字或用户输入空行。在循环内部存储所选择的电影,例如在列表中,计算用户在循环内部或在选择所有想要的电影之后的总价格。