【问题标题】:Why can't I call this method in my program?为什么我不能在我的程序中调用这个方法?
【发布时间】:2025-12-24 17:15:06
【问题描述】:

我对 Java 很陌生,我正在尝试制作一个聊天机器人。我有一个主要方法,然后是一个带有响应的方法。虽然当我尝试在 main 方法中调用 response 方法时,它突出显示了 Response 一词并说:类 ChatCode 中的方法 Response 不能应用于给定类型; 必需:java.lang.String;发现:没有参数;原因:实际参数列表和形式参数列表的长度不同

public class ChatCode{
public static String main(String input){
    Scanner sc = new Scanner(System.in);
    System.out.println("Hello!");
    input = sc.nextLine();
    while(input != ("Bye")){
        Response();
    }
    System.out.println("Bye!");
}

那么这是我的回应方式

public static String Response(String output){
    Scanner sc = new Scanner(System.in);
    input = input.toLowerCase();
    input = input.trim();
    String output;
    if(input.indexOf("hi!") >= 0
    || ("hi") >= 0
    || ("hello!") >= 0
    || ("hello") >= 0){
        output = "Hello!";
    }
    else if(input.indexOf("whats up?") >= 0
    || ("what's up?") >= 0
    || ("whats up") >= 0
    || ("what's up") >= 0){
        output = "Nothing much, how about you?";
    }
    else if(input.indexOf("how are you?") >= 0
    || ("how are you") >= 0){
        output = "I am great, how about you?";
    }
    return output;
}

任何反馈将不胜感激!!!!

【问题讨论】:

  • (0) input != ("Bye") -> How do I compare strings in Java?; (1) Response(String output){ 需要参数,所以你不能通过Response() 调用它; (2) 方法名应以小写开头。
  • 您的方法public static String Response(String output){ 被声明为需要String 参数,但您使用的是Response();,这不是一回事,您必须将其传递给null 或@ 987654331@值
  • 这里需要传入一个String,while(input != ("Bye")){ Response(); // 像这样 -> Response(input); }

标签: java string methods


【解决方案1】:

Response(String output) 方法接受一个参数并且您没有向该方法传递任何参数,对该方法的有效调用是Response("stringValue"); 而不是Response();

此外,正如 (Pshemo) input != ("Bye") 的评论中所述,将比较 String 的引用而不是值。您应该使用"Bye".equals(input)"Bye".equalsIgnoreCase(input) 来检查输入。

【讨论】:

    【解决方案2】:

    您的程序中有很多不正确的地方。
    1.while(input != ("Bye")){
    要比较 2 个字符串对象,请使用 equals() 方法而不是使用 !=。
    while(!("Bye").equals(input)){
    2. 您应该在 Response(String output) 方法中也收到编译错误,因为您还在该方法中创建了一个同名变量。
    3.if(input.indexOf("hi!") >= 0 || ("hi") >= 0 || ("hello!") >= 0 || ("hello") >= 0){ output = "Hello!"; }
    我假设您已经编写了 'input.indexOf("hi") >= 0' 而不仅仅是 '("hi") >= 0'。
    4.查看代码,我认为您不需要在Response方法中将String输出作为参数传递。只需删除此参数并添加一个 else 块,该块将为输出变量设置默认值。

    【讨论】:

      【解决方案3】:

      您声明Response() 方法需要String 类型的单个参数。这意味着在编写时,您需要在调用它时传递一个String。这就是编译器告诉您的:它强制执行您在编写方法时指定的要求。它的沟通效率不是很高(编译器是不会说话的野兽),但现在您知道该消息的含义了。

      由于您从不在函数内部使用参数(而是使用同名的局部变量),只需将其从函数定义中删除,然后您就可以在不带参数的情况下调用Response()

      希望你仔细阅读所有的答案;您的代码还有一些其他问题。

      【讨论】:

        【解决方案4】:

        那是因为你声明了 Response 方法如下

        public static String Response(String output){...}
        

        当你调用它时,你需要遵循格式并传递一个参数。参数类型必须是“字符串”。

        Response(passAnyStringYouWantHere);
        

        【讨论】:

          最近更新 更多