JAVA题目请高手帮忙看看

来源:百度知道 编辑:UC知道 时间:2024/06/11 22:53:34
//接受键盘输入,将输入内容的前3个字符舍去,只显示从第4位开始的内容。
//如果不足4位,则显示空。例如:输入abcd,在控制台显示字母d,
//如果只输入abc,则显示null。
public class NO3 {
public static void main(String[] args){
InputStreamReader dis = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(dis);
try {
if (bis.readLine().length() == 3) {
System.out.println("null");
}else{
bis.skip(3);
System.out.println(bis.readLine());}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
请高手帮忙看下哪里不对,我这样写,如果当我输入3个字符的时候,如ABC,是回返回null,但是,如果当我写超过3个字符时,如ABCD,他会什么都不返回.可是按照我IF条件语句中的意思,应该是说,bis.realline().length表示的是字符穿的长度,如果是3个字符的话,就显示NULL,如果不是,则显示BIS.SKIP(3)跳过3位显示.
但是现在运行后发现的结果是超过3位就不显示任何东西,正好3位则显示NULL.请高手指点我下。哪错了.
那如果说我把这个流重制以下呢?
用bir.reset;
那么流应该会返回之前的数据吧,那应该就有数据了吧?
那我应该怎么写呢?我试着加上过,可是没有作用.
请高手指点下,如何写才正确呢?(可否写给我看下?谢谢)
*最好是在我写的这个上面做改动。应为我还在学习阶段.很多高手用

因为你第一次调用readLine()时候实际上是已经读了一行了,这时候流已经跳到了下一行(如果有的话)。我估计你也没有下一行了,所以自然就得到空值了

“流”这种东西你一旦读取了,位置就变了,切记

那个reset方法有问题,最好不要用,推荐先读取那个字符串,针对字符串操作,不要针对流操作。

String str = bis.readLine();
if(str.length() <= 3) {
System.out.println("null");
} else {
for (int i = 3; i < str.length(); i++) {
System.out.print(str.charAt(i));
}
}

import java.util.*;

public class Test{

public static void main(String [] args) {

Scanner scan = new Scanner(System.in);
System.out.print("Input a string: ");
String line = scan.nextLine();
String result = ((line.length() >= 4) ? line.substring(3,line.length()) : null);
System.out.println("Result is: " + result);
}
}