How do i check if my array contains a word that has spaces in it?

254 views Asked by At
int num;
num = in.nextInt();
String array[] = new String[num];
for (int i = 0; i < num; i++) {
    array[i] = in.next();
    if (array[i].equals("hey guys"))
        System.out.println("hey guys");
    else
        System.out.println("buzz");
}

This is the code i tried. When i remove the space in "hey guys", it works allright but otherwise it doesn't.

2

There are 2 answers

1
Ratish Bansal On

You can use contains() method from String class to check if the string has spaces in it.But from what I understood,you are facing the issue while reading the string with spaces.You should read in using in.nextLine()

int num;
num=in.nextInt();
String array[]=new String[num];
for(int i=0;i<num;i++){
array[i]=in.nextLine();
if(array[i].contains(" "))
//contains space
else 
System.out.println("buzz");}
1
Rajan saha Raju On

Just use in.nextLine() instead of in.next(). It will take line input including spaces.

int num;
num = in.nextInt();
String array[] = new String[num];
for (int i = 0; i < num; i++) {
    array[i] = in.nextLine();
    if (array[i].equals("hey guys"))
        System.out.println("hey guys");
    else
        System.out.println("buzz");
}