数组响应输出

pcww981p  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(226)

所以我在做一个有趣的项目,会问你一系列问题,根据你的回答,给出一个具体的结果。嗯,我已经得到了第一个输出答案,但我不知道该怎么办。
这是源代码。我似乎无法正确输入问题的代码。

import java.util.Scanner;

public class Questionaire {
   public static void main(String[] args) {

   Scanner in = new Scanner(System.in);
   String answers[] = new String[1];
   String response[] = new String[5];

   System.out.println (" Good Evening, Devin. How are you today? "); 
   answers [0] = in.nextLine();

   response [0] = "I'm good";
   response [1] = "I'm okay";
   response [2] = "I'm alright";
   response [3] = "I'm great";
   response [4] = "good";

      if (answers[0].equals (response.length)) {
         System.out.println (" That's awesome! What would you like to talk about?" );
      }
      else {
         System.out.println( " Oh, well then.." );
      }
   }
}

输出:

Good Evening, Devin. How are you today? 
I'm okay
 Oh, well then..

基本上,我试图让if语句将用户输入的内容放入answer[0]数组中,如果他们用response数组中的任何一个响应进行响应,就会得到第一个system.out,但是每当我输入其中的任何一个时,就会不断得到else输出。有人能告诉我我做错了什么吗?

jfgube3f

jfgube3f1#

您希望从中查找用户输入的匹配项 response 数组。 if (answers[0].equals (response.length)) 永远不会评估 true 除非用户输入是 5 因为您正在将用户输入与 response.length 哪个值是 5 . 您需要从中的每个元素循环 response 或者干脆改变

if (answers[0].equals (response.length))

if(Arrays.asList(response).contains(answer[0]))

您需要添加 import java.util.Arrays

7d7tgy0s

7d7tgy0s2#

answers[0].equals (response.length)

此代码将为false,因为答案[0]是与response.length匹配的字符串,response.length为5。如果您想检查答案与响应存在然后代码需要修改如下

Boolean checkresponse=false;
for(int i=0;i<response.length;i++){
                  if (answers[0].equalsIgnoreCase(response[i])) {
                       System.out.println (" That's awesome! What would you like to talk   about?" );
                       checkresponse=true;
                       break;
                    }
              }
              if(checkresponse==false)
                  System.out.println( " Oh, well then.." );

相关问题