DJmendy DJmendy - 26 days ago 7
Java Question

Reading same input twice, in two different methods

I have two separate methods, in two different classes. I want them both to read the same line of input and check for different things. One looks for Instructions like "make me a coffee" and the other looks for different keywords like "please" and "thank you" (these effect how the programme responds to me):

public class Class1(){

public void PleaseAndThankYous(){
Scanner scanner1 = new Scanner(System.in)
input1 = Scanner1.nextLine();

if (input1.contains//blah blah blah blah...


public class Intructions(){

public void Method2(){
Scanner scanner2 = new Scanner(System.in)
input2 = Scanner2.nextLine();

if (input1.contains//blah blah blah blah...


and then I'm calling them in my main string, just to test them:

System.out.println("this is a test, ask me something")
obj.PleaseAndThankYous();
obj.Intructions();


and my console prints out like this:

this is a test, ask me something //(out put string)
make me a coffee please //PleaseAndThankYous() reads this
make me a coffee please // Intructions() reads this;
Making you a coffee, Sir. // (response)


I understand whats going on, but I can't think of another way.
I've also tried using the same Scanner, with different Strings and it still didn't work.
How can I make it so that both methods read my first line of input and I don't have to type everything twice? Thanks!

Answer

Right now you have two methods like this:

public void method() {
    Scanner scanner = new Scanner(System.in)
    input = Scanner.nextLine();

    if (input.contains //blah blah blah blah...

Change them both so they take an argument:

public void method(String input) {        
    if (input.contains //blah blah blah blah...

Then in your main method pass the input you want them to read, so instead of:

method1();
method2();

Use:

Scanner in = new Scanner(System.in);
String input = Scanner.nextLine();
method1(input);
method2(input);

Basically, getting the same string multiple times from a Scanner is not really supported. But you can very easily get the value once and then use it multiple times in different places by passing it as an argument.

This is also better in several other respects - it will increase performance (since you only declare a scanner and read from it once) and it makes your code more modular, as you can have a class for handling input and another class for processing it, instead of doing both in multiple places.