日期:2014-05-20  浏览次数:20715 次

高分求解决一个java问题!我就剩下40分了,都给了,呵呵。
import   java.io.IOException;

class   TestWhile{
public   static   void   main(String[]   args)   throws   IOException{
char   response;
System.out.println( "Are   you   felling   better   about   "   +
                                                    "programming?(Y   or   N) ");
System.out.flush();
response=(char)System.in.read();
while   (   response   != 'Y '&&   response   !=   'N '   ){
System.out.println( "Invalid   letter. ");
System.out.println( "Enter   only   'Y '   or   'N ' ");
response=(char)System.in.read();  
//System.out.println( "a "   +   response   +   "b ");
}

if(response   == 'Y ')
System.out.println( "I   am   grad. ");
else
System.out.println( "Keep   trying! ");
}
}
/*
但运行结果却是这样:
Are   you   felling   better   about   programming?(Y   or   N)
d
Invalid   letter.
Enter   only   'Y '   or   'N '
Invalid   letter.
Enter   only   'Y '   or   'N '
Invalid   letter.
Enter   only   'Y '   or   'N '
Y
I   am   grad.  

为什么在输入d时,循环了了三次呢,,请说明原因及提出修改方法    
*/

------解决方案--------------------
修改后的代码:

import java.io.*;

class TestWhile{
public static void main(String[] args) throws IOException{
String response;
System.out.println( "Are you felling better about " +
"programming?(Y or N) ");
System.out.flush();
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
response=in.readLine();
while ( !response.equals( "Y ") && !response.equals( "N ") ){
System.out.println( "Invalid letter. ");
System.out.println( "Enter only 'Y ' or 'N ' ");
response=in.readLine();
//System.out.println( "a " + response + "b ");
}

if(response.equals( "Y "))
System.out.println( "I am grad. ");
else
System.out.println( "Keep trying! ");
}
}
------解决方案--------------------
因为,你输入d之后回车,真实的输入是d\r\n,一共3个字符,呵呵
------解决方案--------------------
你输入的一个字符再加上回车 一共是三个字符 回车占两个 所以循环了三次。 用BufferedReader比较保险点
------解决方案--------------------
好像是每天回一次贴可以加10分。
lz不要只会索取,没有奉献哦。