2013-10-24 47 views
0

使用静态方法编写一个类,该方法一次接受一个字符,计算字符数,并在字符不在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); 
} 
+0

你的设置在哪里? – Justin

+0

用户必须输入集合的字符 – Abner

+0

在这种情况下,您的'countChars'方法必须通过集合。你想要什么类型的“集合”? – Justin

回答

0

当你想要逐一接受字符,则需要在countChars功能以外的变量。由于您不使用对象,而只使用静态函数,因此该变量也应该是静态的。所以,像这样:

private static int length = 0; 

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

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

+0

现在有道理,谢谢。 – Abner

+0

谢谢你解释我的代码:) – Abner

0

Char只能容纳一个字符。 A String正在持有一个完整的字符序列。

碰巧一个String有一个方法length()。 ;)