试图用java创建一个测验,但出了点问题。我的程序中有哪些部分搞砸了?

时间:2017-07-15 03:54:47

标签: java

所以我开始掌握java,我正在创建一个小测验作为迷你项目。但是,当我到达我的程序的输入部分时,它会崩溃。发生了什么事? 我也为格式化道歉

import java.util.Scanner;
public class Test {
public static void main(String[] args) 
{
    Scanner in = new Scanner(System.in);
    int score = 0;
    int total = 0;


    System.out.println("Are you ready for a quiz? (Y/N)");
    char answer = in.findInLine(".").charAt(0);
    if (answer == 'Y' || answer == 'y');
    {
        String a = "Barrow";
        String b = "Juneau";
        String c = "Anchorage";
        String d = "Annapolis";


        System.out.println("Alright! Lets get right to it!");
        System.out.println("What is the Capital of Alaska?");
        System.out.println("A: " + a);
        System.out.println("B: " + b);
        System.out.println("C: " + c);
        System.out.println("D: " + d);
        char choice = in.findInLine(".").charAt(0);
            if (choice == 'B' || choice == 'b')
            {
                System.out.println("Good Job! 1 point for you!");
                score = score + 1;
            }
            else
            {
                System.out.println("Incorrect! the answer was actually " + b);
            }

        String e = "Yes";
        String f = "No";
        System.out.println("Alright, Next Question! Can you"
        + " store the value 'cat' in a variable of type int?");
        System.out.println("A: " + e);
        System.out.println("B: " + f);
        char secchoice = in.findInLine(".").charAt(0);
            if (secchoice == 'A' || secchoice == 'a')
            {
                System.out.println("Correct! Good Job!");
                score = score + 1;
            }
            else
            {
                System.out.println("Incorrect");
            }

        System.out.println("What is the result of 2+2X3-5?");
        int result = in.nextInt();
            if (result == 3)
            {
                System.out.println("Correct! Good Job!");
            }
            else
            {
                System.out.println("Incorrect");
            }

        System.out.println("Your total score was " + score + "out of 3");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您在第26行because of the way that findInLine() works上收到NullPointerException。基本上,你已经用完了它在启动时给出的一行输入,并且扫描仪已经高级传递它以找到下一个(不存在)。换句话说,您应该为扫描仪使用另一种方法,或使用完全不同的方法来获取输入。

例如,最好使用这种技术

char answer = in.nextLine().charAt(0);

因为nextLine()will wait until it has more input

当然,你必须想出一些方法来解析用户的输入,以确保它是有效的(即如果他们只能在'Y'和'N'之间选择你处理他们的情况不选择)。

这看起来像

char answer = parseInput(in.nextLine().charAt(0));

其中parseInput(String s)是您自己编写的方法。

就其他方法而言,this tutorial from Oracle可以帮助您入门。