当前位置:主页 > 软件编程 > JAVA代码 >

java基础-给出一个随机字符串,判断有多少字母?多少数字?

时间:2021-02-05 09:27:43 | 栏目:JAVA代码 | 点击:

我这里用到了String类中的toarray[]方法。

当看到字符串和判断,我想到之前学过的c语言中判断字符数组中元素,我就去API中找字符串转换成数组的方法

实现方法不唯一,此方法仅作初学者(自己)参考。。。。。

在String类中一共找到三个转数组的方法

很显然,第三个是想要的方法。

实现代码:

package com.string;

import java.util.Scanner;

public class Character_Judge {
 public static void main(String[] args) {
  System.out.println("请随机输入一段字符串");
  Scanner scan = new Scanner(System.in);
  String str = scan.nextLine();
  char s[] = str.toCharArray();
  int char_num=0;//计算字母
  int num = 0;//计算数字
  int other = 0;//计算其他字符

  for(int i=0;i<s.length;i++)
  {
   if (s[i]<='9'&&s[i]>='0')
    num++;
   else if (s[i]>='a'&&s[i]<='z'||s[i]>='A'&&s[i]<='Z')
    char_num++;
   else
    other++;
  }

  System.out.println("字符有"+char_num+"个;数字有"+num+"个;其他字符有"+other+"个");
 }
}

实现结果:

您可能感兴趣的文章:

相关文章