这是一个示例程序,它使用if语句使用用户输入弹出测试分数。
import java.util.Scanner;
public class testscore
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter test score: ");
int testscore = sc.nextInt();
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
这是我为饮料测试创建的程序
import java.util.Scanner;
public class drinktest
{
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println ("Enter The Amount Of Drinks You've Had: ");
int drinknumber = sc.nextInt();
char sober;
if (drinknumber <=2) {sober = 'A';}
else if (drinknumber <=3) {sober = 'B';}
else if (drinknumber <=4) {sober = 'C';}
else if (drinknumber <=5) {sober = 'D';}
else if (drinknumber >=5) {sober = 'F';}
System.out.println ("Your sobreity grade is: " + sober);
}
}
我遇到的问题是一切正常,直到它告诉我我的变量未初始化的最后一行。我没有在第一个程序中得到错误,据我所知它们是相同的。
我做错了什么?
答案 0 :(得分:1)
就Java编译器所知,可能存在没有满足条件的流程,并且不会初始化此sober
。
只需将您的上一个else if
更改为else
,就可以了:
if (drinknumber <=2) {sober = 'A';}
else if (drinknumber <=3) {sober = 'B';}
else if (drinknumber <=4) {sober = 'C';}
else if (drinknumber <=5) {sober = 'D';}
else {sober = 'F';} // If none of the if's were met, it must be more than 5.
答案 1 :(得分:1)
char sober = 0;
使用上面的代码。
答案 2 :(得分:0)
您必须先初始化sober
变量:
char sober = 'F';
然后,在初始化变量之后,您可以执行if语句。
但现在你不需要检查&#39; F&#39; F&#39;等级(它被初始化为&#39; F&#39;)所以请跳过这一部分:
else if (drinknumber >=5) {sober = 'F';}
之后我们留下:
char sober = 'F';
if (drinknumber <=2) {sober = 'A';}
else if (drinknumber <=3) {sober = 'B';}
else if (drinknumber <=4) {sober = 'C';}
else if (drinknumber <=5) {sober = 'D';}
System.out.println ("Your sobreity grade is: " + sober);