使用if else语句进行评分

时间:2014-09-29 08:59:43

标签: java javascript if-statement

import java.util.Scanner;

public class grade   {
public static void main(String args[])       {

Scanner input = new Scanner(System.in);

double no;
System.out.print("Please enter your CPA: ");

no = input.nextDouble();

if (2.00<=no)//2.00<=CPA<= 2.49
System.out.println("forth class");

else if (2.50<=no)//2.50<=CPA<=2.99
System.out.println("third class");

else if (3.00<=no)//3.00<=CPA<=3.74
System.out.println("second class");

else if (3.74<=no)//(no>=3.75)
System.out.println("first class");

else
     System.out.println("You did not follow the order.");

     }  }

如果我输入例如我输入3.5级它将打印出第4课,如果我给4.00也将打印出第4课。为什么它没有打印出确切的答案?

7 个答案:

答案 0 :(得分:1)

它应该。因为forth class通过以下lodic提供

if (2.00<=no)
 System.out.println("forth class");  // both 3.5 and 4.00 are satisfy this.
                                     // 3.5 >2.00 as well as 4.00>2.00

现在您可以看到您的逻辑不正确。任何大于2.00的值都将满足此要求。

只需更改您的逻辑顺序

if (3.74 <= no) {
    System.out.println("first class");
} else if (3.00 <= no) {
    System.out.println("second class");
} else if (2.50 <= no) {
    System.out.println("third class");
} else if (2.00 <= no) {
    System.out.println("forth class");
} else {
    System.out.println("You did not follow the order.");
}

答案 1 :(得分:0)

你上课是因为3.5和4大于2,你最好在这里使用switch语句。

答案 2 :(得分:0)

对于3.5和4.0,您的第一个条件if (2.00<=no)的评估结果为true。跳过所有其他条款,这是if语句的工作原理: - )

答案 3 :(得分:0)

您只需在if条件中添加&amp;&amp;(和)就像...

if (2.00<=no && no < 2.50)
 System.out.println("forth class");

答案 4 :(得分:0)

它是一个简单的if-else语句问题。你忘了在你的陈述中设置边界(范围值)。

答案 5 :(得分:0)

您正在获得预期的输出,因为您目前只检查它是否超过某个数字,尝试交换订单并在每个语句中添加类似的内容:

if (no>=2.00 && no<=2.49)//2.00<=CPA<= 2.49
System.out.println("forth class");

else if (no>=2.50 && no<=2.99)//2.50<=CPA<=2.99
System.out.println("third class");

else if (no>=3.00 && no<=3.74)//3.00<=CPA<=3.74
System.out.println("second class");

else if (no>=3.75)//(no>=3.75)
System.out.println("first class");

else
System.out.println("You did not follow the order.");

答案 6 :(得分:0)

您必须定义上限和下限

if (3.74 <= no) {
    System.out.println("first class");
} else if (3.74 > no && 3.00 <= no) {
    System.out.println("second class");
} else if (3.00 > no && 2.50 <= no) {  
   System.out.println("third class");
} else if (2.50 > no && 2.00 <= no) {
   System.out.println("forth class");
} else {
   System.out.println("You did not follow the order.");
}