我无法将用户输入的字符串转换为字符数组。每当我将字符串转换为char数组时,它仅显示第一个单词。当我用一些文本初始化String时,此代码成功运行,但我使用扫描仪进行输入,此代码不起作用。基本上我想从用户输入中计算字母,字符,空格等。

public static void main(String[] args)

{
Scanner scan=new Scanner(System.in);

System.out.println("Enter the string");
    String s=scan.next();
 count(s);

 }
 public static void count(String x)
{
int letter=0,digit=0,spaces=0,other=0;
char[] c=x.toCharArray();

for(int i=0;i<x.length();i++)
{
  if(Character.isLetter(c[i]))
  {
   letter ++;
  }
  else if(Character.isDigit(c[i]))
  {
    digit ++;
  }
  else if(Character.isSpaceChar(c[i]))
  {
    spaces ++;
  }
  else
  {
    other ++;
  }
 }
 System.out.println(" the total letter is "+ letter);
 System.out.println(" the total digits is "+ digit);
 System.out.println(" the total spaces is "+ spaces);
 System.out.println("other is "+ other);
}

}

最佳答案

如果您要查找字母和数字等的计数,则不必将字符串转换为字符数组。您只需要在遍历输入字符串时将输入字符串的每个字符转换为字符。下面,我将重写您的count函数:

 public static void count(String x)
 {
    int letter=0,digit=0,spaces=0,other=0;

    for(int i=0;i<x.length();i++)
    {
      if(Character.isLetter(x.charAt(i)))
      {
         letter ++;
      }
      else if(Character.isDigit(x.charAt(i)))
      {
        digit ++;
      }
      else if(Character.isSpaceChar(c[i]))
      {
        spaces ++;
      }
      else
      {
        other ++;
      }
    }
    System.out.println(" the total letter is "+ letter);
    System.out.println(" the total digits is "+ digit);
    System.out.println(" the total spaces is "+ spaces);
    System.out.println("other is "+ other);


}

10-08 07:18
查看更多