开关有问题

目前正在努力理解我的错误消息的含义。我知道它不喜欢我从浮点数变为整数,但我该如何解决呢?


import java.util.Scanner;

public class gradeAverage {

    public static void main (String [] args) {

    Scanner sc = new Scanner(System.in); 

    System.out.println("First test score?");

    float test1 = sc.nextInt();

    System.out.println("Second test score?");

    float test2 = sc.nextInt();

    System.out.println("Third test score?");

    float test3 = sc.nextInt();

    float testAverage = (test1 + test2 + test3)/3;

    System.out.println("Your test average is " + testAverage + ".");

    switch(testAverage) {

        case(97.5 <= testAverage <= 100):

        System.out.println("Grade is an A+");

        break;

        case(93.5 <= testAverage <= 97.49):

        System.out.println("Grade is an A");

        break;

        case(89.5 <= testAverage <= 93.49):

        System.out.println("Grade is an A-");

        default:

        System.out.println("Grade is below an A-");

    }

    }

}

错误


gradeAverage.java:13: error: incompatible types: possible lossy conversion from float to int

switch(testAverage) {

          ^


gradeAverage.java:14: error: bad operand types for binary operator '<='

case(97.5 <= testAverage <= 100):

                                 ^


first type:  boolean

second type: int

2 errors


蓝山帝景
浏览 200回答 3
3回答

月关宝盒

开关盒中不能有范围。如果您有一个带有给定字符串或整数值的开关,则每种情况都会检查开关输入是否与一个值完全匹配。对于案例 100,您应该将其写为 100.0 。如果您确实需要使用范围而不是单个值,请使用 if-elseif-else 子句。在 switch 语句中的每个 case 之后,你需要break;一行来告诉代码离开 switch 语句,否则它将继续读取它们并执行里面的所有操作,不管它前面的 case 是否为真。

富国沪深

在 java中的case语句中不能不使用表达式。switch 语句中使用的变量只能是整数、可转换整数(字节、短、字符)、字符串和枚举。考虑java 中switch-case语句的以下用例:public class Test {public static void main(String args[]) {&nbsp; // char grade = args[0].charAt(0);&nbsp; char grade = 'C';&nbsp; switch(grade) {&nbsp; &nbsp; &nbsp;case 'A' :&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Excellent!");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;case 'B' :&nbsp; &nbsp; &nbsp;case 'C' :&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Well done");&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;case 'D' :&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("You passed");&nbsp; &nbsp; &nbsp;case 'F' :&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Better try again");&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp;default :&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Invalid grade");&nbsp; }&nbsp; System.out.println("Your grade is " + grade);&nbsp; }&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java