目标是:
第1行:A-L
第2行:M-Z编写一个程序,将学生的全名(最后一个)作为输入,并打印出学生应该在的行。第一个名字或姓氏将包含任何空格。输入中只有一个空格,它位于名字和姓氏之间。
我不知道如何让它读取字符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是不正确的。如何解决这个问题以使其读取这些字符列表?
答案 0 :(得分:1)
这样的事情应该有效(未经测试):
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!");
}
答案 1 :(得分:0)
一个简单的解决方案是使用char的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. ");
}