2017-08-18 67 views
-3

这个循环的目的是在一个句点键输入后立即停止,但它不工作,我不明白为什么。为什么这个do-while循环不停止?

import java.io.IOException; 


public class ControlFlowTest { 

public static void main(String[] args) throws java.io.IOException { 
    char ch ; 

    do{ 
     ch = (char) System.in.read(); 
    }while(ch != '.'); 

} 
+6

试着检查'ch' cotains? –

+1

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

+2

[Works for me。](http://ideone.com/bu5wlT) – shmosel

回答

0

您将要使用扫描仪,因为System.in.read()会阻塞,直到输入回车符。试试这个:

import java.io.IOException; 

public class ControlFlowTest { 
    public static void main(String[] args) throws java.io.IOException { 
     char ch ; 

     Scanner scanner= new Scanner(System.in); 
     do { 
      ch = scanner.next().charAt(0); 
     } while(ch != '.'); 
    } 
} 
+0

这会做同样的事情,只会更糟糕。随着您的解决方案输入“abc”。并按Enter键不会退出循环。 – Oleg