[英]Java cannot be resolved to a variable issue
Java 和編碼的新手。 我嘗試在 if-else 語句之外對其進行初始化,以查看是否可以解決問題,但這也不起作用,因為它聲稱變量沒有值。 當我嘗試打印 currentScore 時,我收到 currentScore 無法解析為變量的錯誤消息。 這是我當前的代碼。
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Please input the letter grade you would like to receive:");
char desiredGrade = keyboard.next().charAt(0);
System.out.println("Please put either 'Yes' or 'No' whether or not you know the score for each graded item");
System.out.println("Do you know the grade to Exam 1?");
String doesUserKnowExamOne = keyboard.next();
if (doesUserKnowExamOne.equalsIgnoreCase("Yes")) {
System.out.println("Please input the grade for Exam 1");
double examOneGrade = keyboard.nextDouble();
System.out.println("Please input the weight for Exam 1");
int examOneWeight = keyboard.nextInt();
System.out.println("Do you know the grade to Exam 2?");
String doesUserKnowExamTwo = keyboard.next();
double currentScore = (examOneGrade * examOneWeight) / (examOneWeight);
if (doesUserKnowExamTwo.equalsIgnoreCase("Yes")) {
System.out.println("Please input the grade for Exam 2");
double examTwoGrade = keyboard.nextDouble();
System.out.println("Please input the weight for Exam 2");
int examTwoWeight = keyboard.nextInt();
System.out.println("Do you know the grade to Final Exam?");
String doesUserKnowFinal = keyboard.next();
currentScore = (examOneGrade * examOneWeight) + (examTwoGrade * examTwoWeight) / (examOneWeight + examTwoWeight);
if (doesUserKnowFinal.equalsIgnoreCase("Yes")) {
System.out.println("Please input the grade for Final Exam");
double finalExamGrade = keyboard.nextDouble();
System.out.println("Please input the weight for Final Exam");
int finalExamWeight = keyboard.nextInt();
currentScore = (examOneGrade * examOneWeight) + (examTwoGrade * examTwoWeight) + (finalExamGrade + finalExamWeight) / (examOneWeight + examTwoWeight + finalExamWeight);
} else {
System.out.println("Final Exam not taken yet");
}
} else {
System.out.println("Exam Two and Final Exam not taken yet");
}
} else {
System.out.println("Exam One, Exam Two, and Final Exam not taken yet");
}
System.out.println(currentScore);
}
}
問題是您在第一個if
的 scope 中聲明currentScore
變量,並試圖在 scope 之外讀取它。
嘗試聲明:
double currentScore = 0;
在您的第一個if
然后而不是聲明之上,只需執行以下操作:
currentScore = (examOneGrade * examOneWeight)/(examOneWeight);
在第一個if
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.