我需要对输出进行一些小改动,请帮助我

时间:2010-10-28 10:31:25

标签: java exception-handling

import java.util.regex.*;
import java.io.*;
class Patmatch{

    static String str = "";

    public static void main(String[] args){
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter name to see match");
        try{

            str = br.readLine();
        } catch(IOException e){
            System.out.println("Exception has been occurred" + e);

        }

        try{
            Patternmatch();
        } catch(NomatchException me){
            System.out.println("Exception" + me);
        }
    }

    private static void Patternmatch() throws NomatchException{

        Pattern p = Pattern.compile("ab");
        Matcher m = p.matcher(str);
        while(m.find())
            System.out.print(m.start() + " ");

        throw new NomatchException("no match");

    }
}

class NomatchException extends Exception{

    NomatchException(String s){
        super(s);
    }
}

在上面的代码中,当我输入ab时,它显示位置exaclty为0.But也显示异常。我需要输出,如果我输入ab它应该显示ab。如果我输入像def这样的东西,它必须显示异常。你能帮我吗?

1 个答案:

答案 0 :(得分:1)

以下是更改后的方法:

private static void patternMatch() throws NomatchException{

    final Pattern p = Pattern.compile("ab");
    final Matcher m = p.matcher(str);

    if(m.find()){
        System.out.print(m.group());
    } else{
        throw new NomatchException("no match");
    }

}