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) ;
}
}
为了判断name
字符串输入中的错误,我需要判断字符串是否包含任何空格,因为编译器在接受amount
时抛出java.lang.InputMismatchException
(并且当输入的name
包含空格和另一个字符串时).是否有任何预定义的函数来执行此操作?