DJmendy DJmendy - 1 year ago 68
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(
input1 = Scanner1.nextLine();

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

public class Intructions(){

public void Method2(){
Scanner scanner2 = new Scanner(
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")

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 Source

Right now you have two methods like this:

public void method() {
    Scanner scanner = new Scanner(
    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:



Scanner in = new Scanner(;
String input = Scanner.nextLine();

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download