0

This is the string that i use String [] hi = {"hello","hi","whats up"};

I want the program to display one of the words in the string every time the user types "hi" but my code can't compare the user input and the string

do{
  System.out.println("You:");
  s.next();

  String[] userinput={"hi"};

  if(userinput.equals("hi")){
    Random r = new Random();
    rno = r.nextInt(3);
    System.out.println("bot:"+hi[rno]);
  }
  else{
    System.out.println("Bot:Bye");
  }
}while(true);

please help

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Jasper
  • 21
  • 4
  • You compare a string array with a string so this will never yield true. You might want to make userInput a String or check if the [array contains](https://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) the String "hi" – RonaldFindling May 28 '17 at 12:45
  • Don't edit your code. It invalidates all the answers. – Sotirios Delimanolis May 28 '17 at 14:17

5 Answers5

1

You compare an array of Strings with a String. This will always return false as the types are different.

Instead you could use the contains method of a Collection. Example:

List<String> userInput = Arrays.asList("hi");
if (userInput.contains("hi")) {
    //Do something
}
SilverNak
  • 3,283
  • 4
  • 28
  • 44
  • Oh, yeah, using `.contains()` is probably better than the loopy way I did it. – jimboweb May 28 '17 at 12:48
  • thank you it worked, but i actually need the userinput to be able to be changed for example the user can say "hello" or "hi" and it will still do the first loop, until the user says "bye" or "goodbye" then it will exit the loop. Its sort of like a conversation program. Any help would be appreciated Thank you – Jasper May 28 '17 at 13:03
  • @Jasper Ich think your types are the wrong way round. userInput should bei a String while the list of keywords should be...Well, a List. – SilverNak May 29 '17 at 15:51
0

userinput is String[], you need to compare between String as

userinput[0].equals("hi")
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
0

userinput will never equal "hi" because "hi" is a String object, and userinput is a String[] (string array) object.

If userinput is supposed to be an array (a bunch of strings), then you would need to compare by doing the following:

for(String s:userinput){
    if(s.equals("Hi")){
        //do whatever you want to do when this happens
    }
}

If userinput is always going to be a single string then you should say

String userinput = "Hi";
jimboweb
  • 4,362
  • 3
  • 22
  • 45
0

use Map Instead

Map<String,String>map=new HashMap<String,String>();
map.put("Hello","Hi");
System.out.println(map.get(s.next()).toString());
Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34
0

You are comparing a String Array to a String. Try userInput[0].equals("hi")

Karl Zöller
  • 143
  • 8