Rei
Rei

Reputation: 512

asking for user String input without spaces in java

I need the program to return a message if the user input a string with blank spaces. for example "this is my house" is not allowed, "thisismyhouse" is allowed. right now I use this code to check for blank spaces

    for(int i = 0; i < blabla.length(); i++) {
        if (blabla.charAt(i) == ' ')
            flag++;
        }
    }
    if (flag != 0) {
        System.out.println("input must not contain spaces");
    }

I wonder if there's a built in function like 'blabla.equals' etc for this purpose? or a better way to write this?

Upvotes: 0

Views: 2322

Answers (4)

Sedat Kestepe
Sedat Kestepe

Reputation: 95

A little search would give you the answer but... There is a method defined in String that returns a boolean value for that purpose already.

if (blabla.contains(" ")) {
System.out.println("input must not contain spaces");
}

You can review the methods of String...

Upvotes: 0

Abdul Fatir
Abdul Fatir

Reputation: 6357

Solution 1:

if(input.contains(" "))
   System.out.println("input must not contain spaces");

Solution 2:

if(input.indexOf(" ")>=0)
   System.out.println("input must not contain spaces");  

Solution 3:

You can simply allow the user to enter spaces and remove them yourselves instead:

 input = input.replaceAll(" ","");

Upvotes: 1

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

this should do the trick.

if(blabla.contains(" ")){};

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44834

try

   if (blabla != null && blabla.contains (" ")) {
      System.out.println("input must not contain spaces");
      return;
   } 

Upvotes: 0

Related Questions