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 otherwise java.lang.InputMismatchException is thrown when it accepts amount (and when the entered name contains whitespace with another string).
Is there any predefined function that does this?
You can use the following method to determine if a
Stringcontains a white-space character.Also, you're going to want to test the
namevalue using theString.equalsmethod, as opposed to the==equality operator.Furthermore, the
mainmethod requires a singleStringarray, orStringvarargs parameter, to be valid.Here is a quick demonstration of how I would implement the task.