AnotherUser
AnotherUser

Reputation: 147

How can we read the previous line in console?

Is there a way to read the previous line in the console? My current code prints out Hello, and I want to print another message if it contains or doesn't contain the word?

I wrote an example below. I know there is code required within the if statement but I can't figure what code is needed.

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");
}

Upvotes: 0

Views: 1572

Answers (2)

Hemant Metalia
Hemant Metalia

Reputation: 30648

As ELLiott mentioned you can not read it back but you can track it by storing the data in some variable as follow:

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");
}

Upvotes: 3

ninja.coder
ninja.coder

Reputation: 9648

You can't read back what you printed on console but you can always keep a track by storing it in a variable.

Here is one way of doing it:

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");
}

Upvotes: 0

Related Questions