我需要在String中返回返回值类型。
这是有效的代码:
import java.util.Scanner;
public class Score {
public void Display(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your marks: ");
int newPoint = input.nextInt();
newPoint = calculateSc(newPoint);
System.out.println(newPoint);
}
public static int calculateSc(int point) {
if (point <= 100 && point >= 80) {
return 1;
}else if (point <= 79 && point >= 60) {
return 2;
}else if (point <= 59 && point >= 50) {
return 3;
}else if (point <= 49 && point >= 40) {
return 4;
}else if (point <= 39 && point >= 30) {
return 5;
}else {
return -1;
}
}
}
这是愿望代码(错误代码):
import java.util.Scanner;
public class Score {
public void Display(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your marks: ");
int newPoint = input.nextInt();
newPoint = calculateSc(newPoint);
System.out.println(newPoint);
}
public static String calculateSc(int point) {
if (point <= 100 && point >= 80) {
return "You got A+";//String value
}else if (point <= 79 && point >= 60) {
return "You got A";
}else if (point <= 59 && point >= 50) {
return "You got A-";
}else if (point <= 49 && point >= 40) {
return "You got B";
}else if (point <= 39 && point >= 30) {
return "You got C";
}else {
return "You got F (failed";
}
}
}
我想大家都明白,我想做什么。如果你有任何正确的解决方案请回答。但是不要改变第二个String方法calculateSc()
答案 0 :(得分:2)
正如您所提到的,您不希望从int更改return方法。
您不能在int方法中返回String,但可以使用System.out.print将其打印出来,或者只是使用方法计算成绩,另一种方法根据等级返回String。
答案 1 :(得分:1)
当你返回String时为什么要将返回类型设置为int?尝试了解有关方法和返回类型的更多信息
public static String calculateSc(int point) {
if (point <= 100 && point >= 80) {
return "You got A+";
} else if (point <= 60 && point >= 70) {
return "You got A";
} else {
return "You got F (Failed)";
}
}
你不能在int变量中赋予String值,remember方法在更改后返回String。所以要替换这两行,
newPoint = calculateSc(newPoint);
System.out.println(newPoint);
只有这个,
System.out.println(calculateSc(newPoint));
答案 2 :(得分:0)
public static int calculateSc(...
int 表示该函数将返回一个int类型。
在工作代码中,所有return语句都返回 int ,整数。
在无效代码中,您尝试返回字符串:字符序列,而不是整数。
函数不能返回声明返回的类型以外的类型。