2013-04-18 16 views
-2

嗨我是新的Java編程,並遇到了我的最新項目的問題。我正在爲保齡球得分發電機和成品的代碼,除非我去測試它,它說如何修復我的掃描儀輸入爲空?

「異常線程‘main’顯示java.lang.NullPointerException 在Bowling_Score.main(Bowling_Score.java:34 )「

我嘗試了一切來修復它,並瀏覽了大量的網站,但沒有解決方案解決了我的問題。這可能很容易解決,但我似乎無法找到答案。有問題的線是此處的第二行。

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

這是我知道如何使用帶有變量的掃描儀的唯一方法,所以如果有更好的方法,請告訴我。這也可能是一個問題,因爲變量Frame1Throw1是列表中的第一個變量。

變量是正確的,我的掃描儀的名字是SC

請使用明確的答案,因爲正如我所說,我是新的java和剛學的基本知識吧。這是我的第一個大項目。

謝謝!

P.S.我使用日食代碼我不知道是否重要

*我得到了一個答案,它是有幫助的,但它沒有奏效。以下是可能有助於回答的代碼的開頭部分。

 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; } 
+0

您可能需要提供更多的代碼才能找到錯誤 –

+0

什麼是Frame1Throw1,您在哪裏初始化它? – Infested

回答

2

A NullPointerException意味着您引用的對象尚未初始化。所以在這種情況下,我想象你的代碼中以前沒有創建過你的sc

查找類似

Scanner sc; 

,並更改爲

Scanner sc = new Scanner(System.in); 

否則,它可能是一個範圍問題(您創建的對象的地方,不能由該方法可以看出),你如果第一個解決方案不起作用,則需要提供更多的代碼。

+0

謝謝,但它沒有工作。我添加了一些可能有用的代碼 – user2294866

+0

從查看您的代碼,我可以看出您沒有初始化您的掃描儀。將'private static Sc​​anner sc'行更改爲'private static Sc​​anner sc = new Scanner(System.in);',這應該可以解決您的問題。 – TheMerovingian

+0

或者嘗試在'main()'函數中創建整個對象。即使用我在回答中提供的線路 – TheMerovingian