首页 > 解决方案 > 如果 lastName 的第一个字符在 A 和 M 之间,我如何返回 1,如果 N 到 Z,我如何返回 2?

问题描述

如果 lastName 的第一个字符在 A 和 M 之间,我需要修复 getLineNumberFor 方法以返回 1,否则如果它在 N 和 Z 之间,则返回 2。

在我的脑海中听起来很容易,但我不确定我应该在这里使用什么。不确定我是否应该使用 charAt。

import java.util.Scanner;

public class ConferenceRegistration {


    /**
     * Assists in guiding people to the proper line based on their last name.
     *
     * @param lastName The person's last name
     * @return The line number based on the first letter of lastName
     */
    public int getLineNumberFor(String lastName) {
        int lineNumberOne = 1;
        int lineNumberTwo = 2;
        Scanner scanner = new Scanner(System.in);
        lastName = scanner.nextLine();
        char guess = lastName.charAt(0);

        if(lastName >= 'm'){
            return lineNumberOne;
        }
        else{
            return lineNumberTwo;
        }
    /*
      lineNumber should be set based on the first character of the person's last name
      Line 1 - A thru M
      Line 2 - N thru Z

     */

    }
}

标签: java

解决方案


尝试

if(guess <= 'm'){

这将让您只比较 中的第一个charString因为><比较在chars 上工作正常(因为它们基本上可以像 一样比较int),但对于String.

请注意,它<=不是>=因为 Java char a < b < z。有关详细信息,请参阅ASCII 表。此外,如果您不希望用户输入“?”,则需要添加更多逻辑。得到 1,或“-”得到 2。


推荐阅读