2014-02-21 44 views
0

我是一個半小老闆程序員,我想做岩石剪刀,但它給了我這個錯誤異常在線程「主」java.lang.NullPointerException,在stensakspapir.main(stensakspapir.java:34)

"Exception in thread "main" java.lang.NullPointerException, atstensakspapir.main(stensakspapir.java:34)" 

,並從我已經解決,我需要選擇1和2的賭注之後刪除「=空」,那麼它給了我這個錯誤

The local variable choice1 may not have been initialized, The local variable choice2 may not have been initialized

import java.util.Scanner; 


public class stensakspapir { 

    @SuppressWarnings("null") 
    public static void main(String[] args) {  

    @SuppressWarnings("unused") 
    String userChoice, 
    choice1 = null, 
    choice2 = null, 
    compare, 
    computerChoice2; 


    @SuppressWarnings("resource") 
    Scanner scanner1 = new Scanner (System.in); 

    System.out.println("Do you choose rock, paper or scissors?"); 
    userChoice=scanner1.nextLine(); 

    int computerChoice1 = 
    (int)(Math.random()*100); 
    if (computerChoice1 < 34) { 
     computerChoice2 = "rock"; 
    } else if(computerChoice1 <= 67) { 
     computerChoice2 = "paper"; 
    } else { 
     computerChoice2 = "scissors"; } 

    compare = function(choice1, choice2);{ 
     System.out.println("The computer chose " + computerChoice2); 
      if (choice1.equals(choice2)){ 
       System.out.println("The result is a tie!"); 
      }else if (choice1.equals("rock"));{ 
       if (choice2.equals("scissors")) 
        System.out.println("rock wins"); 
         else{System.out.println("Paper wins");} 
      }if (choice1.equals ("scissors")){ 
       if (choice2.equals("rock")) 
        System.out.println("scissors wins"); 
         else{System.out.println("Paper wins");} 
      }else if (choice1.equals ("paper")){ 
       if (choice2.equals("rock")) 
        System.out.println("Paper wins"); 
         else{System.out.println("Scissors wins");} 
      }else { 
       System.out.println("paper wins");} 
    }; 

    compare(userChoice, computerChoice1); 
} 


    private static void compare(String userChoice, int computerChoice1) { 

    } 

    private static String function(String choice1, String choice2) { 

     return null; 
    } 


} 
+1

什麼是第34行?該行上的某些內容包含空引用,這是錯誤的。你不會通過壓制警告和刪除適當的初始化代碼來解決這個問題 - 研究什麼是例外情況並解決問題的原因! – Gimby

+0

那些被壓制的警告實際上會讓你很難找到問題的根源,因爲警告通常會很好地指向正確的方向。 –

+0

你也想檢查'main'中'compare'的定義。這不是在Java中定義函數的有效方法。將它移入類定義中。 –

回答

0
  The null value is not compare with other.like equals 

      Remove this 

      String userChoice, 
      choice1 = null, 
      choice2 = null, 

      Replace this 

      String userChoice, 
      choice1 = "", 
      choice2 = ""; 

enter image description here

本程序被加工

如果(選擇1.equals(選擇2)),可變選擇1並不是指一個對象時程序到達
+0

如何在網上運行程序,我試着在www.Ideone.com上運行,但是,我無法運行。它在錯誤類中講述。 – jmail

0

。它仍然是空的。要調用非靜態方法,必須創建一個對象。 coice1必須被賦予一個String對象的引用。順便說一下,局部變量必須被初始化(不像實例變量被賦予默認值)。否則代碼將無法編譯。

+0

你可以maby顯示如何?謝謝 :) – user3329288

相關問題