我们如何在控制台中读取前一行?

时间:2016-03-16 11:09:59

标签: java console

有没有办法在控制台中读取上一行?我当前的代码打印出Hello,我想打印另一条消息,如果它包含或不包含该单词?

我在下面写了一个例子。我知道if语句中需要代码,但我无法确定需要什么代码。

System.out.println("Hello");

if (something){ 
    System.out.println("Line above contains the word Hello");
}
else(!something){
    System.out.println("Line above does not contain the word Hello");
}

2 个答案:

答案 0 :(得分:3)

正如ELLiott所说,你无法读回来但你可以通过将数据存储在某个变量中来跟踪它,如下所示:

String line="Hello";
System.out.println(line);

if (line.contains("Hello")){ 
   System.out.println("Line above contains the word Hello");
}
else{
  System.out.println("Line above does not contain the word Hello");
}

答案 1 :(得分:0)

您无法回读在控制台上打印的内容,但您可以通过将其存储在变量中来保持跟踪。

这是一种方法:

String something = "Hello";
System.out.println(something);

if (something.contains("Hello")) { 
    System.out.println("Line above contains the word Hello");
} else {
    System.out.println("Line above does not contain the word Hello");
}