Determine if char value is in range of chars

后端 未结 2 1801
梦谈多话
梦谈多话 2021-01-27 06:55

The objective is this:

Row 1: A-L
Row 2: M-Z

Write a program that takes as input a student\'s full name (first last) and prints out the

相关标签:
2条回答
  • 2021-01-27 07:46

    Something like this should work (not tested):

    if((initial >= 'A' && initial <= 'L') || (initial >= 'a' && initial <= 'l')){
        // If letter is between 'A' and 'L' or 'a' and 'l'
        System.out.println(" This student can sit anywhere in row 1. ");
    } else if((initial >= 'M' && initial <= 'Z') || (initial >= 'm' && initial <= 'z')){
        // If letter is between 'M' and 'Z' or 'm' and 'z'
        System.out.println(" This student can sit anywhere in row 2. ");
    }
    

    And if the input would be full name add this:

    try{
        char initial = name.split(" ")[1].charAt(0);
    } catch(Exception e){
       System.out.println("Invalid input!");
    }
    
    0 讨论(0)
  • 2021-01-27 07:50

    An easy solution would be to use the ascii value of the char.

    int m = (int)'M';
    name = name.toUpperCase();
    int initial = (int)name.charAt(0);
    
    if(initial < m)
    {
        System.out.println(" This student can sit anywhere in row 1. ");
    }
    else
    {
        System.out.println(" This student can sit anywhere in row 2. ");
    }
    
    0 讨论(0)
提交回复
热议问题