Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何计数字符和打印计数_Java_Exception Handling - Fatal编程技术网

Java 如何计数字符和打印计数

Java 如何计数字符和打印计数,java,exception-handling,Java,Exception Handling,使用静态方法编写一个类,该方法一次接受一个字符,统计字符数,如果字符不在集合{'a'..'z',0'..'9',a'..'z}中,则引发异常。应该抛出异常但不捕获(即,没有显式的catch块)。编写一个调用此方法的客户端程序,如果该方法引发异常,则打印“输入错误” 我的问题是,如何计算输入字符并打印它们 import java.util.*; public class Format { public static int countChars(char c) throws Excep

使用静态方法编写一个类,该方法一次接受一个字符,统计字符数,如果字符不在集合{'a'..'z',0'..'9',a'..'z}中,则引发异常。应该抛出异常但不捕获(即,没有显式的catch块)。编写一个调用此方法的客户端程序,如果该方法引发异常,则打印“输入错误”

我的问题是,如何计算输入字符并打印它们

import java.util.*;

public class Format {

    public static int countChars(char c) throws Exception {
        int count = 0;


        if (!Character.isLetterOrDigit(c)) {
            throw new Exception("Input Error");
        }

        return count;

    }
    public static void main(String[] args) {
        char c = ' ';
        int length = 0;

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a String: ");
        while (input.hasNext()) {
                String line = input.nextLine();
                for (int i = 0; i < length; i++) {
                    try{
                    countChars(line.charAt(i));
                }catch(Exception e){
                    System.out.println("Wrong Character");
                    System.out.println(e.getMessage());
                    System.exit(0);
                }
            }
        }
    }
  //  System.out.println("Count: " + count);
}
import java.util.*;
公共类格式{
公共静态int countChars(char c)引发异常{
整数计数=0;
if(!Character.isleterordigit(c)){
抛出新异常(“输入错误”);
}
返回计数;
}
公共静态void main(字符串[]args){
字符c='';
整数长度=0;
扫描仪输入=新扫描仪(System.in);
System.out.println(“请输入字符串:”);
while(input.hasNext()){
String line=input.nextLine();
for(int i=0;i
要逐个接受字符,需要在
countChars
函数之外添加一个变量。因为您使用的不是对象而是静态函数,所以该变量也应该是静态的。比如说:

private static int length = 0;

public static int countChars(char c) throws Exception {
  length++;
  //...
}

然后,您也可以从主函数访问可变长度。

Char
只能包含一个字符。
字符串
包含整个字符序列


碰巧,
字符串
有一个名为
length()
;的方法

用户必须为集合输入字符。在这种情况下,您的
countChars
方法必须传递集合。你想要什么类型的“集合”?你的实际问题是什么?(你的countChars方法打算做什么?)对不起,我不明白你的问题。