如何使用only if语句编写这个程序

epggiuax  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(332)
Scanner n = new Scanner(System.in);
System.out.println("Enter english marks");

double en =n.nextInt();
                System.out.println("Enter maths marks");

double mt = n.nextInt();
System.out.println("Enter scinece marks");

double sc = n.nextInt();

double percentage;

percentage = (en+mt+sc)/3;
System.out.println("Percentage is: "+percentage);

if(en>33 && mt>33 && sc>33){
    if(percentage>40){

        System.out.println("Pass");

     }else
            System.out.println("fail");
     }else{
         System.out.println("fail");
2cmtqfgy

2cmtqfgy1#

在这种情况下,有多个if和else并没有错。尽管如此,如果您执行以下操作,您只能获得一次成功:

String message_to_print = "fail";
if(percentage>40 && en>33 && mt>33 && sc>33){
   message_to_print = "Pass";
System.out.println(message_to_print);
d8tt03nd

d8tt03nd2#

你好nikhil,欢迎来到stackoverflow。
回答您的问题,您只需要将嵌套的if条件添加到外部if。
想想看,你有一个条件 en>33 && mt>33 && sc>33 . 如果这个条件是真的,那么还有另一个条件 percentage>40 .
我们打电话吧 en>33 && mt>33 && sc>33 条件1和 percentage>40 条件2。
伪代码如下:

if(condition1)
  if (condition2)
    //Only enter here if condition1 and condition2 are true
    pass
  else
    not pass
else
  not pass
``` `condition2` 只有当它本身是真实的并且 `condition1` 我也是。所以你可以先加入

if (condition1 && condition2)
//Only enter here if condition1 and condition2 are true
pass
else
not pass

因此,您的最终java代码将是:

if(en>33 && mt>33 && sc>33 && percentage>40){
System.out.println("Pass");
}else{
System.out.println("fail");
}

相关问题