Вопрос

I am trying to write a method that prints out whatever character the user is entering character by character appended with the previous ones as he enters and throws an exception when he presses enter. I have written the following code but when i enter, it appends what ever character I have written and does not throw an exception. I would appreciate your help and suggestion.

public static void inputM(StringBuffer a) throws EntExc, IOException{
              char c;
       String m;
    while(true){
       Scanner s = new Scanner(System.in);

       m=s.next();
       c=m.charAt(0);

        if(c=='\r'){
            throw new EntExc();
        }
        System.out.println(a.append(m));
    }
}
Это было полезно?

Решение

There are a few issues here. First s.next() grabs a whitespace-delimited token and returns the entire token as a single string. Second, because Scanner uses whitespace as a delimiter, it will never return \r, it will just skip it and read the next token.

Why not use s.readLine() and simply echo the whole line? While it won't process characters as they are entered (Scanner can't really do this, it always buffers lines), it will be closer to your described requirement.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top