【问题标题】:For loop character [closed]For循环字符[关闭]
【发布时间】:2013-07-19 11:48:42
【问题描述】:

我遇到了一个问题。当我键入一个名称时,例如:“大卫”。它成功终止,但是当我输入名称为“大卫”时,它显示错误。你们对此有什么想法/解决方案吗?

import java.util.Scanner;
public class test {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System. in );
        String name;
        int length;
        char alpha;
        boolean status = true;

        do {
            System.out.print("Enter name : ");
            name = sc.nextLine();
            length = name.length();

            for (int count = 0; count < length; count++) {
                alpha = name.charAt(count);

                if (alpha < 'a' || alpha > 'z')
                    System.out.print("Error");
                status = (true);
            }


        } while (status == false);

    }
}

【问题讨论】:

  • 计算机可以识别大小写之间的差异,就像大多数人类一样。

标签: java for-loop char character


【解决方案1】:

要检查一个字符是否不是字母,你可以使用-

if(!Character.isLetter(alpha))
    System.out.print("Error");
status = true;
....
...

【讨论】:

    【解决方案2】:

    你已经检查了

     if(alpha < 'a' || alpha > 'z' )
                System.out.print("Error");
                status = (true);
     }
    

    当你输入“大卫”时,“D”是大写字母,那么它在你的条件下返回 false

    价值
    97
    z 122
    D 68

    这清楚地表明 D(68) 是

    【讨论】:

    • 请不要误导 OP。这与 ASCII 无关。请改为指向 Unicode 代码点列表。
    猜你喜欢
    • 2011-09-07
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多