确定字符值是否在字符范围内

Determine if char value is in range of chars

objective是这样的:

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 row the student should be in. The first nor last name will contain any spaces. There will be only one space in the input and that will be between the first and last name.

我不确定如何让它读取字符 A - L 和 M- Z。

import java.util.Scanner;

public class SeatingChart {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        char row1 = 'A' ,'L';
        char row2 = 'M' ,'Z';

        System.out.println(" Enter the student's last name: ");
        String name = in.next();

        char initial = name.charAt(0);

        if (initial = row1) {
            System.out.println(" This student can sit anywhere in row 1. ");
        }

        if (initial = row2) {
            System.out.println(" This student can sit anywhere in row 2. ");
        }

        in.close();
    }
}

这是我目前所拥有的,但是代码对于声明字符 A - L 和字符 M - Z 是不正确的。我该如何解决这个问题以使其读取这些字符列表?

一个简单的解决方案是使用字符的 ascii 值。

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

这样的东西应该可以工作(未测试):

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

如果输入是 完整 名称,请添加:

try{
    char initial = name.split(" ")[1].charAt(0);
} catch(Exception e){
   System.out.println("Invalid input!");
}