I am writing a program where I need to check if a string (name) contains any whitespaces or not.
Here’s part of my program :
public static void main()
{
Scanner sc = new Scanner(System.in) ;
String name = "" ;
boolean error = false ;
do {
if(error) System.out.println("Sorry, error. Try again") ;
error = false ;
System.out.print("Enter your name : ") ;
name = sc.next() ;
if(name=="") error = true ;
} while(error) ;
double amount = 0.00 ;
do {
if(error) System.out.println("Sorry, error. Try again") ;
error = false ;
System.out.print("Enter amount of purchase : ") ;
amount = sc.nextDouble() ;
if(amount<=1) error = true ;
} while(error) ;
}
}
For checking errors in the name string input, I need to check if the string contains any whitespaces or not because the compiler throws java.lang.InputMismatchException when it accepts amount (and when the entered name contains whitespace with another string). Is there any predefined function that does this ?
>Solution :
You can use the following method to determine if a String contains a white-space character.
boolean containsSpace(String string) {
for (char character : string.toCharArray()) {
switch (character) {
case ' ', '\t', '\n', '\r', '\f' -> {
return true;
}
}
}
return false;
}
Also, you’re going to want to test the name value using the String.equals method, as opposed to the == equality operator.
if (name.equals("")) error = true;
Furthermore, the main method requires a single String array, or String varargs parameter, to be valid.
public static void main(String[] args)