简单的Java程序

时间:2013-04-07 16:17:48

标签: java runtime-error

我正在研究一个程序,但遇到了运行时问题。该程序有效,但是,在我选择电影并对其进行评级后,它应该只给出平均评分并回到开头并让用户选择另一部电影。相反,它转到默认(else语句)。之后,它允许用户选择另一部电影。我试过多次重写它,但它仍然一直显示这个问题,我做错了什么?我该如何解决?

import java.text.DecimalFormat;
import java.util.Scanner;


public class movie {
    Scanner s1=new Scanner(System.in);
    private String movielist, movie;
    private double userR;
    public String pg="rated PG-13", r="rated R";
    public String rate="Rate this movie 1-5, 1 being terrible and 5 great";
    public String crm1="Score       1   2   3   4   5\n# of Raters 1   3   1   3   12",crm2="Score       1   2   3   4   5\n# of Raters 4   2   4   6   4", crm3="Score       1   2   3   4   5\n# of Raters 3   0   5   5   7";
    DecimalFormat userR1=new DecimalFormat("#.#");


    public String m1(){
        System.out.println("\nChoose one of the following movies\nJurassic Park, Identity Theft, The Dark Night");
        movielist=s1.nextLine();
        if(movielist.equalsIgnoreCase("Jurassic Park"))
        {
            System.out.println("Jurassic Park is "+pg+"\nCritics rated this movie: \n"+crm1+"\n"+rate);
            userR=s1.nextDouble();System.out.println("With your rating, the average rating for this movie is: "+(userR1.format((82+userR)/21)));
        }
        else if(movielist.equalsIgnoreCase("Identity Theft"))
        {
            System.out.printf("Identity Theft is "+r+"\nCritics rated this movie: \n"+crm2+"\n"+rate);
            userR=s1.nextDouble();
            System.out.println("With your rating, the average rating for this movie is: "+(userR1.format((68+userR)/21)));
        }
        else if(movielist.equalsIgnoreCase("The Dark Night"))
        {
            System.out.printf("The Dark Night is "+pg+"\nCritics rated this movie: \n"+crm3+"\n"+rate);
            userR=s1.nextDouble();
            System.out.println("With your rating, the average rating for this movie is: "+(userR1.format((73+userR)/21)));
        }
        else 
        {
            System.out.println("No movie with that name found, make sure your spelling is correct.");
        }
        return m1();
    }
}

1 个答案:

答案 0 :(得分:0)

问题是,nextDouble()会读取一个数字,但不会读取下面的换行符。例如,在阅读评分后添加nextLine()电话或将nextDouble()替换为Double.parseDouble(s1.nextLine())

另一方面,除了源代码中不存在的格式之外,还有其他一些问题,最重要的是你的程序永远不会终止,直到它最终因为你的堆栈空间不足而崩溃。如果这是学校作业,你也应该尝试解决这个问题。