我有一段时间没有使用java,由于某种原因,我不知道如何初始化我的方法和对象没有错误。这是我遇到麻烦的两个:
// setLetterGrades Method
public static setLetterGrades(ArrayList<Integer> scores){
ArrayList<Integer> grades = new ArrayList<Integer>();
for (int i = 0; i < scores.size(); i++){
if (score >= 90 && score < 101){
String grade = "A";
}
else if (score >= 80 && score < 90){
String grade = "B";
}
else if (score >= 70 && score < 80){
String grade = "C";
}
else if (score >= 60 && score < 70){
String grade = "D";
}
else if(score > 60 && score <= 0){
String grade = "F";
}
else {
String grade = "Invalid test score.";
}
grades.add(grade);
}
return grades;
}
我得到"语法错误,插入"EnumBody"完成第一行的BlockStatement:public static setLetterGrades(ArrayList<Integer> scores){
同样,我在这个对象的第一行得到'语法错误on token "public", new expected':
// GradeBook Object
public GradeBook(ArrayList<Integer> scores, testName){
String test = testName;
ArrayList<Integer> testScores = ArrayList<Integer> scores;
setLetterGrades();
}
我如何使第二个对象更"object-y"然后改正错误?谢谢你的帮助!
您忘记了方法的返回类型:
public static ArrayList<String> setLetterGrades(ArrayList<Integer> scores){
您忘记了ArrayList构造函数的new
关键字。这不是科特林!
ArrayList<Integer> testScores = new ArrayList<>();
但我认为你想做的是:
ArrayList<String> testScores = setLetterGrades(scores);
// setLetterGrades Method
// Specifies the return type ## public static ArrayList<String> ##
public static setLetterGrades(ArrayList<Integer> scores){
// The grade variable is of type String, so we need a list of Strings.
ArrayList<Integer> grades = new ArrayList<Integer>();
for (int i = 0; i < scores.size(); i++){
// Define the score variable
if (score >= 90 && score < 101){
String grade = "A";
}
else if (score >= 80 && score < 90){
String grade = "B";
}
else if (score >= 70 && score < 80){
String grade = "C";
}
else if (score >= 60 && score < 70){
String grade = "D";
}
else if(score > 60 && score <= 0){
String grade = "F";
}
else {
String grade = "Invalid test score.";
}
// Here, when calling the grade variable, it is not initialized.
grades.add(grade);
}
return grades;
}
我的答案
// setLetterGrades Method
public static ArrayList<String> setLetterGrades(ArrayList<Integer> scores){
ArrayList<String> grades = new ArrayList<String>();
String grade = "";
for (int i = 0; i < scores.size(); i++){
int score = scores.get(i);
if (score >= 90 && score < 101){
grade = "A";
}
else if (score >= 80 && score < 90){
grade = "B";
}
else if (score >= 70 && score < 80){
grade = "C";
}
else if (score >= 60 && score < 70){
grade = "D";
}
else if(score > 60 && score <= 0){
grade = "F";
}
else {
grade = "Invalid test score.";
}
grades.add(grade);
}
return grades;
}
和我对第二个问题的看法
// GradeBook Object
public GradeBook(ArrayList<Integer> scores, testName){
String test = testName;
ArrayList<String> grades = setLetterGrades(scores);
}