import java.util.Scanner; /** * 2.编写一个java程序,提示用户输入一个字符串,要求字符串中必须存在字母(需要代码判断) a. 若不符合要求,则提示用户重新输入直到符合要求为止 b. 若符合要求 ,则判断字符串中的大写字母出现的次数并且打印 */public class Test02 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true){ System.out.println("输入一个字符串,要求字符串中必须存在字母"); String string = scanner.next(); boolean method1 = method1(string); //如果包含字母 if(method1){ int sum = method2(string); System.out.println(sum); break; } } } /** * 需要统计大写字母的字符串 * @param s * @return */ public static int method2(String s){ int sum = 0; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { if(chars[i] <= ‘Z‘ && chars[i] >= ‘A‘){ System.out.println(chars[i]); //出现大写字母加1 sum++; } } return sum; } /** * 首先判断输入的是否包含字母 * 该方法适用于检测字符串中是否包含字母(z-a,Z-A) * @param s 需要检测的字符串 * @return 是否有字母 true 是有字母 false 没有字母 */ public static boolean method1(String s){ //先把字符串变为字符数组 char[] chars = s.toCharArray(); //遍历数组 for (int i = 0; i < chars.length; i++) { //包含字母的情况 if((chars[i] <= ‘Z‘ && chars[i] >= ‘A‘) || (chars[i] >= ‘a‘ && chars[i] <= ‘z‘)){ return true; } } return false; }}
原文地址:https://www.cnblogs.com/YRSWBY2016/p/12000053.html
时间: 2024-08-03 21:29:39