[英]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.