【问题标题】:How to find the number of characters in a string in java如何在java中查找字符串中的字符数
【发布时间】:2016-12-23 22:28:53
【问题描述】:

以下代码仅输出“输入字符串”并接受用户输入,但不显示字符串中的字符数。请帮忙!

System.out.println("Enter a string");
Scanner scan = new Scanner(System.in);
String result = scan.nextLine();


try {
 while (a != null) {
  count++;
 }
} catch (Exception e) {
 System.out.println("Invalid string");
}

System.out.println("The number of characters are : " + count);

【问题讨论】:

  • 请详细说明你希望你的程序一步一步做什么。
  • 你有一个非常明显的无限循环。

标签: java


【解决方案1】:

您可以使用String.length() 来计算输入字符串的长度:

    System.out.println("Enter a string");
    Scanner scan = new Scanner (System.in);
    String a = scan.nextLine();

    System.out.println("The number of characters are : " + a.length());

【讨论】:

    【解决方案2】:

    oschlueter 是对的。此外,当使用java.util.Scanner 从用户输入中获取字符串时,您不需要 try/catch 来查找无效字符串,因为用户可以输入的任何内容都可以是字符串。但是,通过Scanner.nextInt 询问号码时,您将需要 Try/Catch。

    此外,通常建议捕获特定错误,而不仅仅是 Exception。在这种情况下,您会捕捉到java.util.InputMismatchException

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多