以下是用Java编写的程序,实现输入一串小写字符,再输入一个数字,然后打印出现数字个数的字母:

import java.util.Scanner;

public class PrintLetters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一串小写字符:");
        String inputString = scanner.nextLine();
        
        System.out.print("请输入一个数字:");
        int num = scanner.nextInt();
        
        if (num <= 0) {
            System.out.println("数字必须大于0!");
            return;
        }
        
        if (num > inputString.length()) {
            System.out.println("数字超过字符串长度!");
            return;
        }
        
        System.out.printf("出现%d次的字母有:", num);
        printLetters(inputString, num);
    }
    
    public static void printLetters(String inputString, int num) {
        int[] count = new int[26];  // 26个小写字母的计数数组
        
        // 统计每个字母出现的次数
        for (int i = 0; i < inputString.length(); i++) {
            char c = inputString.charAt(i);
            if (c >= 'a' && c <= 'z') {
                count[c - 'a']++;
            }
        }
        
        // 打印出现num次的字母
        for (int i = 0; i < count.length; i++) {
            if (count[i] == num) {
                System.out.print((char)('a' + i) + " ");
            }
        }
    }
}

使用示例:

请输入一串小写字符:abcdefghijklaabbccdd
请输入一个数字:3
出现3次的字母有:a b c
``
用java写出程序:输入一串小写字符输入一个数字打印出现数字个数的字母

原文地址: https://www.cveoy.top/t/topic/h5lZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录