使用静态方法编写一个类,该方法一次接受一个字符,计算字符数,并在字符不在set {'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);
}
你的设置在哪里? – Justin
用户必须输入集合的字符 – Abner
在这种情况下,您的'countChars'方法必须通过集合。你想要什么类型的“集合”? – Justin