-2

嗨,我是 Java 编程新手,在我的最新项目中遇到了问题。我正在为保龄球制作一个分数生成器并完成了代码,除非我去测试它,它说

“Bowling_Score.main (Bowling_Score.java:34) 处的线程“主”java.lang.NullPointerException 中的异常”

我尝试了一切来解决它,并浏览了大量的网站,但没有解决方案解决我的问题。这可能很容易解决,但我似乎找不到答案。有问题的行是这里的第二行。

    System.out.println("Frame 1, Throw 1");
    Frame1Throw1 = sc.nextInt();

这是我知道如何使用带变量的扫描仪的唯一方法,所以如果有更好的方法请告诉我。这也可能是一个问题,因为变量 Frame1Throw1 是列表中的第一个变量。

变量是正确的,我的扫描仪的名字是 sc

请具体回答,因为正如我所说,我是 Java 新手,现在只是学习基础知识。这是我的第一个大项目。

谢谢你!

PS我使用eclipse来编码我不知道这是否重要

*我得到了一个答案,它很有帮助,但它没有用。这是代码开头的更多内容,可能有助于回答。

     import java.util.Scanner;
    public class Bowling_Score {

     private static Scanner sc;
public static void main(String[] args) {
//All Variables
    int Frame1Throw1 = 0;
    int Frame1Throw2 = 0;
    int Frame2Throw1 = 0;
    int Frame2Throw2 = 0;
    int Frame3Throw1 = 0;
    int Frame3Throw2 = 0;
    int Frame4Throw1 = 0;
     //Then I have one variable for each throw of the game, and one for the final total score.
        //Directions
    System.out.println("To put in your score, put the number of pins you  knocked down in the throw specified. If you get a strike, enter a 10 in the first throw of the frame and a 0 in the second throw of the frame. If you get a spare, Ener a 0 in the first throw of the frame and 10 in the second throw of the frame.");

    //Frame 1
    System.out.println("Frame 1, Throw 1");
    Frame1Throw1 = sc.nextInt();
    if (Frame1Throw1 == 10){
        Frame1Throw1 = Frame1Throw1 + Frame2Throw1 + Frame2Throw2;
        Frame1Throw2 = 0; }
4

1 回答 1

2

ANullPointerException表示您引用的对象尚未初始化。所以在这种情况下,我想你sc之前没有在你的代码中创建过。

寻找类似的东西

Scanner sc;

并将其更改为

Scanner sc = new Scanner(System.in);

否则可能是范围问题(您在该方法看不到的地方创建了对象),如果第一个解决方案不起作用,您将需要提供更多代码。

于 2013-04-18T11:52:05.427 回答