我有这个评分程序,我正在尝试使用键盘输入退出程序的很多东西,在这种情况下是字母“E”。我创建了另一种方法,但我不能让它与main方法一起工作,而且我是如此新,以至于我被困住了。我尝试使用布尔值,并使用字符串转换为int,但我得到的只是错误。我的代码在下面,提前谢谢你,我知道这可能是一个愚蠢的问题。
import java.util.Scanner;
public class grading {
public static void main (String args[]){
boolean run = true;//this code together with bottom keep loop running
while(run){ //the code inside this brackets will continue the loop
int yourScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter your Score: ");
yourScore = input.nextInt();
boolean kill;
System.out.println("Press E to Exit");
Scanner input0 = new Scanner(System.in);
if (yourScore < 60 && yourScore >=0){
System.out.println("You had an F, Sorry!");
}
else if (yourScore >=60 && yourScore < 70){
System.out.println("You had an D, Study more!");
}
else if (yourScore >=70 && yourScore < 80){
System.out.println("you had an C, you can do Better!");
}
else if (yourScore >= 80 && yourScore < 90){
System.out.println("You had an B, very Well done!");
}
else if ( yourScore >=90 && yourScore <= 100){
System.out.println("you had an A, you are Great!");
}
else if (kill = "e" != null){
System.out.println("Bye!");
Runtime.getRuntime().exit(0);
}
else
System.out.println("Incorrect Input!");
}
}
}
答案 0 :(得分:0)
您的代码中有几处错误。首先,您允许用户输入数字和字母,但将输入分配给您的分数是int。如果用户输入一个字母,那么您试图将该字母指定为整数,这会抛出InputMismatchException。
其次,您正在使用两个扫描仪,但从不使用第二个扫描仪(即输入0)。实际上,您在此程序中不需要两个Scanner。只有一台扫描仪可以完成这项工作。
第三,在最后一个if语句中,你要分配kill =&#34; e&#34; != null。我很确定这不是你打算做的。您应该首先熟悉java的工作原理。在java中,执行从右到左进行。在这里表达&#34; e&#34;首先评估!= null。因为&#34; e&#34;是一个字符串,它永远不会等于null。因此,表达&#34; e&#34; != null将评估为true。然后将此真值分配给kill变量。因此,无论如何,kill变量总是如此。这不是你想要的。以下是可以按预期工作的代码。
public class grading {
public static void main (String args[]){
boolean run = true;//this code together with bottom keep loop running
while(run){ //the code inside this brackets will continue the loop
int yourScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter your Score or E to exit: ");
//checking if the input is integer or not
if(input.hasNextInt()){
yourScore = input.nextInt();
if (yourScore < 60 && yourScore >=0){
System.out.println("You had an F, Sorry!");
}
else if (yourScore >=60 && yourScore < 70){
System.out.println("You had an D, Study more!");
}
else if (yourScore >=70 && yourScore < 80){
System.out.println("you had an C, you can do Better!");
}
else if (yourScore >= 80 && yourScore < 90){
System.out.println("You had an B, very Well done!");
}
else if ( yourScore >=90 && yourScore <= 100){
System.out.println("you had an A, you are Great!");
}
else
System.out.println("Incorrect Input!");
}
// checking if the input is string
else if(input.hasNext()){
//assigning input to String varible
String userInput = input.next();
//comparing the input value with letter e ignoring the case
if(userInput.equalsIgnoreCase("e")){
run = false;
}
else{
System.out.println("Invalid key. Press e to exit");
}
}
}
}
}