[英]Cannot be resolved to a variable println
我收到此錯誤: Exception in thread "main" java.lang.Error: Unresolved compilation problem: studentName cannot be resolved to a variable
我不知道出了什么問題或如何解決它。 錯誤在代碼底部,第二個 println System.out.println(studentName);
. 任何幫助都會很棒。
import java.util.Scanner;
public class allDone {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String studentNames = "";
String studentScores = "";
while (true){
//Prompt user to enter Student Name.
System.out.println("Please Enter StudentName or If Finished Enter alldone:");
String studentName = in.nextLine();
if (studentName.equals("alldone")){
break;
}
studentNames = studentNames + studentName +";";
System.out.println("Please enter student's score:");
String studentScore = in.nextLine();
studentScores = studentScores + studentScore + ";";
}
String studentNamesArry[] = studentNames.split(";");
int studentScoresArry[] = getStudentArry(studentScores.split(";"));
displayHighestScore(studentNamesArry,studentScoresArry);
}
public static int[] getStudentArry(String[] stringArray){
int[] studentScoresArry = new int [stringArray.length];
int i = 0;
for (String str: stringArray){
studentScoresArry[i] = Integer.parseInt(str.trim());
i++;
}
return studentScoresArry;
}
public static void displayHighestScore(String studentNamesArry[],int studentScoresArry[]){
int studentScore = studentScoresArry[0];
for (int i = 1; i < studentScoresArry.length; i++){
if (studentScoresArry[i] > studentScore){
studentScore = studentScoresArry[i];
String studentName = studentNamesArry[i];
}
}
System.out.println("nHighestScore:");
System.out.println(studentName);
System.out.println(studentScore);
}
}
這能解決您的問題嗎?
public static void displayHighestScore(String studentNamesArry[],int studentScoresArry[]){
if(studentNamesArry.length > 0 && studentScoresArry.length > 0){
int studentScore = studentScoresArry[0];
String studentName = studentNamesArry[0];
for (int i = 1; i < studentScoresArry.length; i++){
if (studentScoresArry[i] > studentScore){
studentScore = studentScoresArry[i];
studentName = studentNamesArry[i];
}
}
System.out.println("nHighestScore:");
System.out.println(studentName);
System.out.println(studentScore);
}
}
注意:我添加了一個 if 語句來檢查 arrays 是否為空。
您只需要提前初始化 studentName ,因為 if 語句可能無法初始化它
public static void displayHighestScore(String studentNamesArry[],int studentScoresArry[])
{
int studentScore = studentScoresArry[0];
String studentName="";
for (int i = 1; i < studentScoresArry.length; i++)
{
if (studentScoresArry[i] > studentScore)
{
studentScore = studentScoresArry[i];
studentName = studentNamesArry[i];
}
}
System.out.println("nHighestScore:");
System.out.println(studentName);
System.out.println(studentScore);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.