Java 用两种不同的方法读取同一输入两次

Java 用两种不同的方法读取同一输入两次,java,input,methods,Java,Input,Methods,我有两个不同的方法,在两个不同的类中。我想让他们都读同一行输入,检查不同的东西。一个查找“为我煮咖啡”之类的说明,另一个查找不同的关键字,如“请”和“谢谢”(这些影响程序对我的反应): 然后我在主字符串中调用它们,只是为了测试它们: System.out.println("this is a test, ask me something") obj.PleaseAndThankYous(); obj.Intructions(); 我的控制台显示如下: this is a test, ask m

我有两个不同的方法,在两个不同的类中。我想让他们都读同一行输入,检查不同的东西。一个查找“为我煮咖啡”之类的说明,另一个查找不同的关键字,如“请”和“谢谢”(这些影响程序对我的反应):

然后我在主字符串中调用它们,只是为了测试它们:

System.out.println("this is a test, ask me something")
obj.PleaseAndThankYous();
obj.Intructions();
我的控制台显示如下:

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)
public void method() {
    Scanner scanner = new Scanner(System.in)
    input = Scanner.nextLine();

    if (input.contains //blah blah blah blah...
我明白发生了什么,但我想不出别的办法。 我也尝试过使用相同的扫描仪,不同的字符串,但仍然不起作用。
我怎样才能使这两种方法都能读取我的第一行输入,而不必键入所有内容两次?谢谢

现在有两种方法:

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)
public void method() {
    Scanner scanner = new Scanner(System.in)
    input = Scanner.nextLine();

    if (input.contains //blah blah blah blah...
将两者都更改,以便他们进行辩论:

public void method(String input) {        
    if (input.contains //blah blah blah blah...
然后在main方法中传递您希望它们读取的输入,因此,不要:

method1();
method2();
使用:

基本上,不支持从扫描仪多次获取相同的字符串。但是,通过将其作为参数传递,您可以很容易地获得一次值,然后在不同的位置多次使用它


这在其他几个方面也更好-它将提高性能(因为您只声明一个扫描器并从中读取一次),并且它使您的代码更加模块化,因为您可以有一个用于处理输入的类和另一个用于处理输入的类,不要在多个位置同时执行这两项操作。

阅读
main
中的输入,然后将字符串作为参数传递给
PleaseAndThankYous
Intructions
@DJmendy乐意帮助!