Правильный формат для вложенных операторов if-else

#java #if-statement #do-while

#java #if-statement #do-while

Вопрос:

 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, task, title, 
                        JOptionPane.INFORMATION_MESSAGE);
                task= "End of Program!";
                JOptionPane.showMessageDialog(null, task, title, 
                        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 annadmissible Roman numeral ", title,
                        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 annadmissible Roman numeral ", title,
                            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, "Input "   roman  
                        " is not annadmissible Roman numeral ", title,
                        JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0); 
                }
            }
            else {
                JOptionPane.showMessageDialog(null, "Input "   roman  
                    " is not annadmissible Roman numeral ", title,
                    JOptionPane.INFORMATION_MESSAGE);
                System.exit(0); 
            }
            
            str= String.format("The decimal value for the Roman numeral ""  roman   "" is: ....."
                      "%d"   "....." , decimal);
            JOptionPane.showMessageDialog(null, str, title, 
                    JOptionPane.INFORMATION_MESSAGE);
                
            
            
            yesNo= JOptionPane.showConfirmDialog(null, "Any more Roman Numerals?n",
                    title, JOptionPane.YES_NO_OPTION);
                


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

        System.exit(0);
    }

}
  

Предполагается, что код считывает римские цифры и отображает их как соответствующее числовое значение. Это работает для всех римских цифр, начинающихся с «X», но каждый раз, когда я ввожу единицу, начинающуюся с «I» или «V», программа переходит к последнему оператору «else». У меня возникают трудности с правильным форматированием вложенных операторов if-else.

Комментарии:

1. почему бы не поместить I и V в else if?

2. Я пробовал это раньше, и это вызвало проблемы с отображением оператора в конце, который отображает числовое значение в диалоговом окне сообщения

3. Примечание — в вашем коде вы проверяете, если roman.equals("IX") и если да, вы устанавливаете decimal = 10 , но римская цифра IX на самом деле равна 9 .

Ответ №1:

Возьмем, например, меньший пример:

 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);
  

Одним из способов обойти это было бы изменить оператор catch-all else на:

 // 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);
}
  

Ответ №2:

Код работает нормально..

Приведенный ниже код работает нормально. Я смог распечатать:

 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);
    }

}