黑马程序员技术交流社区
标题:
刚写的程序代码,出了问题,大家帮帮吗
[打印本页]
作者:
XinWen
时间:
2014-4-29 12:10
标题:
刚写的程序代码,出了问题,大家帮帮吗
package day29;
import java.io.IOException;
import java.io.InputStream;
public class INDemo {
public static void main(String[] args) {
// 定义 流 引用
InputStream _InputStream = null;
//每次读入的数据
int _Ch = 0;
//缓冲区
StringBuilder _Buff = new StringBuilder();
try{
_InputStream = System.in;
while(true){
_Ch = _InputStream.read();
if( ((char)_Ch) == '\r')
continue;
if( ((char)_Ch) == '\n' ){
if(_Buff.toString().equals("over"))
return;
System.out.println(_Buff.toString());
_Buff.delete(0, _Buff.length());
}
_Buff.append((char)_Ch);
}
}catch(IOException e){
}
}
}
复制代码
在输入 over 的时候,第一次可以成功结束,但是如果前面输入了其他字符,就不管用了
作者:
今生无憾
时间:
2014-4-29 12:53
本帖最后由 今生无憾 于 2014-4-29 13:11 编辑
因为你先输入其他字符后,换行会有换行的空字符串出现。。所以与 over 字符匹配时总是false。
if(_Buff.toString().trim().equals("over"))
return; 去掉换行空格再比较。就OK了
作者:
eternallove
时间:
2014-4-29 13:06
import java.io.IOException;
import java.io.InputStream;
public class INDemo {
public static void main(String[] args) {
// 定义 流 引用
InputStream _InputStream = null;
//每次读入的数据
int _Ch = 0;
//缓冲区
StringBuilder _Buff = new StringBuilder();
try{
_InputStream = System.in;
while(true){
_Ch = _InputStream.read();
if( _Ch == '\r')
continue;
if( _Ch == '\n' ){
String str =_Buff.toString();
if("over".equals(str))
break;
System.out.println(str);
_Buff.delete(0, _Buff.length());
}
else
_Buff.append((char)_Ch);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
复制代码
解决了,没问题了
作者:
﹊佑雨时杰↘
时间:
2014-4-29 13:08
楼主你好 :
根据你写的代码 我加了一句话: continue;
public static void main(String[] args) {
// 定义 流 引用
InputStream _InputStream = null;
//每次读入的数据
int _Ch = 0;
//缓冲区
StringBuilder _Buff = new StringBuilder();
try{
_InputStream = System.in;
while(true){
_Ch = _InputStream.read();
if( ((char)_Ch) == '\r')
continue;
if( ((char)_Ch) == '\n' ){
if(_Buff.toString().equals("over")){
return;
}
System.out.println(_Buff.toString());
_Buff.delete(0, _Buff.length());
continue;
}
_Buff.append((char)_Ch);
}
}catch(IOException e){
}
}
复制代码
因为你每次读取字符\n 后 又给_Buff执行 _Buff.append((char)_Ch); , 加入了字符\n 所以会有换行。 也就不能.equals("over") 了 。。 不知道我的 解释你能懂不。。。。
作者:
程序爱好者
时间:
2014-4-29 13:20
while(true){
_Ch = _InputStream.read();
if( ((char)_Ch) == '\r')
continue;
if( ((char)_Ch) == '\n' ){
if(_Buff.toString().equals("over"))
return;
System.out.println(_Buff.toString());
_Buff.delete(0, _Buff.length());
continue; //[color=Red]加个continue就OK了[/color]
}
_Buff.append((char)_Ch);
}
复制代码
作者:
XinWen
时间:
2014-4-29 15:00
程序爱好者 发表于 2014-4-29 13:20
太 感谢了 ,自己 琢磨了 半天
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2