0
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.

Robert
  • 33,260
  • 14
  • 84
  • 130
  • [Read it carefully](https://stackoverflow.com/questions/22458575/whats-the-difference-between-next-and-nextline-methods-from-scanner-class) you should use nextLine() method. – Rajan saha Raju Jan 19 '19 at 11:57

2 Answers2

1

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");
}
Manoj Choudhari
  • 4,179
  • 2
  • 15
  • 27
Rajan saha Raju
  • 537
  • 4
  • 12
0

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");}
Ratish Bansal
  • 1,197
  • 5
  • 17