如何在if/else语句Java中包含数字范围 [英] How to have a range of numbers in an if/else statement Java

查看:68
本文介绍了如何在if/else语句Java中包含数字范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过一系列解释和练习来学习Java,其中之一是创建一个程序,该程序根据多个点(0–29、30–30)显示数字等级(0-5).34、35-39、40-44、45-49、50-60).

I'm learning Java through a series of explanations and exercises, and one of them was to create a program that would display a number grade (0-5) in accordance to a number of points (0–29, 30–34, 35–39, 40–44, 45–49, 50–60).

System.out.println("Type the points [0-60]: ");
double points = reader.nextDouble();
reader.nextLine();
if (points < 29) {
    System.out.println("Grade: FAILED.");
} else if (points <= 34) {
    System.out.println("Grade: 1.");
} else if (points <= 39) {
    System.out.println("Grade: 2.");
} else if (points <= 44) {
    System.out.println("Grade: 3.");
} else if (points <= 49) {
    System.out.println("Grade: 4.");
} else if (points >= 50) {
    System.out.println("Grade: 5.");
}

该程序的工作方式是,由于命令中的重叠,它将给出正确的等级,但是有什么方法可以创建一系列满足if/else语句条件的数字或字符串?例如,如果输入的数字在40-44之间,依此类推.由于我是新手,所以请提供详细的答案.

The program works in that it'll give the correct grade because of the overlap in commands, but is there any way to create a range of numbers or strings that could meet the condition of the if/else statement? For example, if the number entered is between 40-44 and so on. Detailed answer would be appreciated since I'm new.

推荐答案

如果要测试数字是否介于某些值之间,请使用逻辑运算符AND用于if语句,例如:

If you want to test if number is between some values use logical operator AND for if statements like:

if(points>=40 && points <=45)

为更加清晰起见,我建议您进行如下所示的控件反转:

To get more clarity I would suggest you to make a control inversion like this:

    int grade;
    if(points >49){
        grade=5;
    }else if(points >44){
        grade=4;
    }else if(points >39){
        grade=3;
    }else if(points >34){
        grade=2;
    }else if(points >29){
        grade=1;
    }else{
        grade=0;

  }
    System.out.println("Gr: "+grade); //grade=0 = not passed

这篇关于如何在if/else语句Java中包含数字范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆