嵌套if-else语句的正确格式

如何解决嵌套if-else语句的正确格式

package lab04_AnnaStineburg;

//import java.util.Scanner;
import javax.swing.JOptionPane;

public class RomanNumerals {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String task;
        String title;
        String roman;
        int yesNo;
        int decimal;
        String str;
        
        
        task= "Enter a Roman Numneral between \"I\" and \"XX\"";
        title=  "Conversion of Roman Numerals";
        
        do {
            
            roman= JOptionPane.showInputDialog(null,task,title,JOptionPane.QUESTION_MESSAGE);
            
            if(roman==null) {
                task= "You pressed Cancel Button";
                JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
                task= "End of Program!";
                JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
                
                System.exit(0);
            }
            
            
            roman= roman.toUpperCase();
            decimal =0;
            
            if (roman.charAt(0)== 'I') {
                if (roman.equals("I")) {
                    decimal= 1;
                }
                else if(roman.equals("II")) {
                        decimal= 2;
                }
                else if(roman.equals("III")) {
                    decimal=3;
                }
                else if(roman.equals("IV")) {
                    decimal= 4;
                }
                else if(roman.equals("IX")) {
                    decimal= 10;
                }
                else {
                    JOptionPane.showMessageDialog(null,"Input " + roman +
                        " is not an\nadmissible Roman numeral ",JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0); 
                }
            }
            
            if(roman.charAt(0)== 'V') {
                if (roman.equals("V")) {
                    decimal= 5;
                }
                else if(roman.equals("VI")) {
                    decimal= 6;             
                }
                else if(roman.equals("VII")) {
                    decimal= 7;
                }
                else if(roman.equals("VIII")) {
                    decimal=8;
                }
                else {
                    JOptionPane.showMessageDialog(null,"Input " + roman +
                            " is not an\nadmissible Roman numeral ",JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0); 
                    
                }
    
            }
             
             
            if(roman.charAt(0)=='X') {
                if(roman.equals("X")) {
                    decimal= 10;
                }
                else if(roman.equals("XI")) {
                    decimal=11;
                }
                else if(roman.equals("XII")) {
                    decimal=12;
                }
                else if(roman.equals("XIII")) {
                    decimal=13;
                }
                else if(roman.equals("XIV")) {
                    decimal=14;
                }
                else if(roman.equals("XV")) {
                    decimal=15;
                }
                else {
                    JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0); 
                }
            }
            else {
                JOptionPane.showMessageDialog(null,"Input " + roman +
                    " is not an\nadmissible Roman numeral ",JOptionPane.INFORMATION_MESSAGE);
                System.exit(0); 
            }
            
            str= String.format("The decimal value for the Roman numeral \""+ roman + "\" is: ....."
                    + "%d" + ".....",decimal);
            JOptionPane.showMessageDialog(null,str,JOptionPane.INFORMATION_MESSAGE);
                
            
            
            yesNo= JOptionPane.showConfirmDialog(null,"Any more Roman Numerals?\n",JOptionPane.YES_NO_OPTION);
                


        } while (yesNo==0);
    
        task= "End of program!";
        JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);   

        System.exit(0);
    }

}

该代码应读取罗马数字并将其显示为相应的数值。它适用于所有以“ X”开头的罗马数字,但是每次我输入以“ I”或“ V”开头的数字时,程序都会进入最后的“ else”语句。我在正确格式化嵌套的if-else语句时遇到困难。

解决方法

以一个较小的示例为例:

String roman = "IV";
int decimal = 0;

if (roman.charAt(0) == 'I') {
    if (roman.equals("IV") {
        decimal = 4;
    } else {
        decimal = 1;
    }
}

if (roman.charAt(0) == 'V') {
    if (roman.equals("VI") {
        decimal = 6;
    } else {
        decimal = 5;
    }
} else {
    System.out.println("Error incorrect roman numeral entry");
    System.exit(0);
}

System.out.println("Roman numeral: " + roman + " = " + decimal);

您希望此代码输出Roman numeral IV = 4,但实际上它输出Error incorrect roman numeral entry

这是原因:

// 1 - Start Here
String roman = "IV";
int decimal = 0;

// 2 - roman starts with 'I' so enter 'if'
if (roman.charAt(0) == 'I') {
    // 3 - roman equals "IV" so enter 'if'
    if (roman.equals("IV")) {
        // 4 - set decimal to 4
        decimal = 4;
    } else {
        decimal = 1;
    }
}

// 5 - roman does not start with 'V' don't enter 'if'
if (roman.charAt(0) == 'V') {
    if (roman.equals("VI") {
        decimal = 6;
    } else {
        decimal = 5;
    }
// 6 - enter the catch-all 'else'
} else {
    // 7 - output error message
    System.out.println("Error incorrect roman numeral entry");
    // 8 - exit program
    System.exit(0);
}

System.out.println("Roman numeral: " + roman + " = " + decimal);

一种解决方法是将“包罗万象”其他语句更改为:

// earlier code ...

if (roman.charAt(0) == 'V') {
    if (roman.equals("VI") {
        decimal = 6;
    } else {
        decimal = 5;
    }
// if decimal still equals 0 then no proper roman numeral was read
} else if (decimal == 0) {
    System.out.println("Error incorrect roman numeral entry");
    System.exit(0);
}
,

代码可以正常工作。

以下代码可以正常工作。我能够打印:

inside IV if
The decimal is: 4

//import java.util.Scanner;
//import javax.swing.JOptionPane;

public class RomanNumerals {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String roman = "IV";
        int decimal = 0;

        roman = roman.toUpperCase();

        if (roman.charAt(0) == 'I') {
            if (roman.equals("I")) {
                System.out.println("inside I if");

                decimal = 1;
            } else if (roman.equals("II")) {
                decimal = 2;
            } else if (roman.equals("III")) {
                decimal = 3;
            } else if (roman.equals("IV")) {
                System.out.println("inside IV if");

                decimal = 4;
            } else if (roman.equals("IX")) {
                decimal = 10;
            } else {
                System.out.println("Input is not an admissible Roman numeral 1 ");
                System.exit(0);
            }
        }

        else if (roman.charAt(0) == 'V') {
            if (roman.equals("V")) {
                decimal = 5;
            }

            else if (roman.equals("VI")) {
                decimal = 6;
            } else if (roman.equals("VII")) {
                decimal = 7;
            } else if (roman.equals("VIII")) {
                decimal = 8;
            }

            else {
                System.out.println("Input is not an admissible Roman numeral 2");
                System.exit(0);

            }

        }

        else if (roman.charAt(0) == 'X') {
            if (roman.equals("X")) {
                decimal = 10;
            }

            else if (roman.equals("XI")) {
                decimal = 11;
            } else if (roman.equals("XII")) {
                decimal = 12;
            } else if (roman.equals("XIII")) {
                decimal = 13;
            } else if (roman.equals("XIV")) {
                decimal = 14;
            } else if (roman.equals("XV")) {
                decimal = 15;
            }
        } 
        
        else
            System.out.println("Input  is not an admissible Roman numeral 3");

        System.out.println("The decimal is: "+ decimal);
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-