【问题标题】:String function "CharAt" storing and displaying numeric values in "char"字符串函数“CharAt”在“char”中存储和显示数值
【发布时间】:2017-09-17 06:29:55
【问题描述】:

好的,伙计们,我正在使用这个字符串函数“charAT”来存储 charater 变量以存储在 char r 中。但我们知道用户可以输入任何内容。当用户输入像 123 或 5 这样的数值或任何 charAt 将其存储在 char 变量 r 中时。异常应该来了,但它没有。 char 变量如何能够保存数值。我怎样才能解决这个问题?我希望“r”仅保存 char 值,并希望在用户输入数值时发生异常。

package string;

import java.util.Scanner;

public class Example 
{

Scanner s1;
String str;
char r;

Example()
{
  s1 = new Scanner(System.in);
}

void display()
{
    while(true)
    {
    try {

    System.out.println("Please enter the grade");
    str = s1.nextLine();
    r = str.charAt(0);
    System.out.println("The grade is "+ r);
    break;
    }
    catch(Exception e)
    {
        System.out.println("you have entered an invalid input. Please try again \n");
    }
    }
}

public static void main(String[] args)
{
    new Example().display();
}
}

【问题讨论】:

    标签: java.util.scanner charat string-function


    【解决方案1】:

    在 Java 中,Stringchar 的值也可以接受数值。因此,如果您输入 123 作为输入,则字符串将为“123”,字符将为 1。如果您只想获取字母作为输入,那么您可以使用 Java 的 Scanner 类中的 hasNext 方法来完成。这将使用Regular Expression,例如[A-Za-z],以确保只能提供字母作为输入。

    while(true)
    {
        try
        {
            System.out.println("Please enter the grade");
            while (!s1.hasNext("[A-Za-z]+")) {
                System.out.println("you have entered an invalid input. Please try again \n");
                s1.next();
            }
            str = s1.next();
            r = str.charAt(0);
            System.out.println("The grade is "+ r);
            break;
        }
        catch (Exception e)
        {
            System.out.println("There was an exception \n");
        }
    }
    

    【讨论】:

      【解决方案2】:

      听起来你需要测试字符是否在某个 ASCII 范围内:

      ascii = (int) str.toLowerCase().charAt(0);
      if ( ( ascii >= (int) 'a' ) && ( ascii <= (int) 'f' ) ) {
          // Valid!
      } else {
          // Invalid!
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多