gpt4 book ai didi

java - 确定 char 值是否在字符范围内

转载 作者:行者123 更新时间:2023-12-02 04:18:35 27 4
gpt4 key购买 nike

目标是这样的:

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 是不正确的。我如何解决这个问题以使其读取这些字符列表?

最佳答案

类似的东西应该可以工作(未经测试):

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

关于java - 确定 char 值是否在字符范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044520/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com