我是一個半小老闆程序員,我想做岩石剪刀,但它給了我這個錯誤異常在線程「主」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;
}
}
什麼是第34行?該行上的某些內容包含空引用,這是錯誤的。你不會通過壓制警告和刪除適當的初始化代碼來解決這個問題 - 研究什麼是例外情況並解決問題的原因! – Gimby
那些被壓制的警告實際上會讓你很難找到問題的根源,因爲警告通常會很好地指向正確的方向。 –
你也想檢查'main'中'compare'的定義。這不是在Java中定義函數的有效方法。將它移入類定義中。 –