问题是我从影评人那里收到了意外错误。
import java.util.Scanner;
public class deTest {
public static void main(String[] args) {
Scanner kbScanner=new Scanner(System.in);
aClass bClass=new aClass();
System.out.print("What is the movie you want to review?... ");
bClass.movies=kbScanner.nextLine();
do{
System.out.print("What would you give it out of 10?... ");
bClass.ratings=kbScanner.nextInt();
if (bClass.ratings>10){
System.out.println("Sorry, your rating went over 10. Please try again...");
}
if (bClass.ratings<=10){
System.out.println("You gave a rating of "+bClass.ratings+".");
}
}while (bClass.ratings>10);
bClass.graderate(bClass.ratings, bClass.grade);
System.out.println("This movie got a grade of "+bClass.grade);
bClass.printInfo(bClass.movies, bClass.ratings, bClass.grade);
}
}
这是类(class):
public class aClass {
String movies;
int ratings;
String grade;
void graderate(int ratings,String grade){
switch (ratings){
case 1:
grade=("C");
break;
case 2:
grade=("C");
break;
case 3:
grade=("C");
break;
case 4:
grade=("B");
break;
case 5:
grade=("B");
break;
case 6:
grade=("B");
break;
case 7:
grade=("A");
break;
case 8:
grade=("A");
break;
case 9:
grade=("A");
break;
case 10:
grade=("A+");
break;
default:
grade=("?");
}
}
void printInfo(String movies,int ratings,String grade){
System.out.println("The movie "+movies+" was given rating of "+ratings+" out of 10 and received a grade of "+ grade);
}
}
我收到的错误是这样的:
What is the movie you want to review?... Titanic
What would you give it out of 10?... 7
You gave a rating of 7.
This movie got a grade of null
The movie Titanic was given rating of 7 out of 10 and received a grade of null
控制台没有给我成绩(它是一个字符串),而是不断将 null 放在成绩的位置。这个错误是在我将 bClass.grade 从字符更改为字符串之后发生的。当 bClass.grade 是一个字符时,我得到:
What is the movie you want to review?... Real Steel
What would you give it out of 10?... 10
You gave a rating of 10.
This movie got a grade of
The movie Titanic was given rating of 10 out of 10 and received a grade of
没有任何东西可以代替成绩。那么,我对我的影评人做错了什么?
最佳答案
graderate(...)
中的参数 grade
隐藏了类 aClass
的 grade
实例,所以您在 switch
中修改的是局部变量 grade
(parameter) ,而不是字段。没有必要传递它,因为 grade
是类的一个字段:
void graderate(int ratings)
{
switch (ratings)
{
case 1:
case 2:
case 3:
grade = ("C");
break;
case 4:
case 5:
case 6:
grade = ("B");
break;
case 7:
case 8:
case 9:
grade = ("A");
break;
case 10:
grade = ("A+");
break;
default:
grade = ("?");
}
}
并在您的 main
方法中调用它:
bClass.graderate(bClass.ratings);
注意,您可以通过“分组案例”来简化您的switch
,这样您就不会重复代码(看看上面的修改,很简单)。
关于java - '无效的'?类(class)分配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199359/