用java编写一个程序要求检查输入的字符串中间是否有空格,如果有则抛出异常并返回信息

如题所述

第1个回答  2012-05-11
String ss="aa aaa aa";
String[] arr=ss.split(" ");
System.out.println(arr.length);
if(arr.length>1){
System.out.println("有空格");
}else{
try {
throw new Exception();
} catch (Exception e) {
}
}
第2个回答  2012-05-11
看看是不是这样的:
public static void main(String[] args) {
check("sfsfs sfsfs");

}
public static void check(String str){
String[] s = str.split("");
for (int i = 0; i < s.length; i++) {
if(" ".equals(s[i])){
try {
throw new Exception();
} catch (Exception e) {
System.err.println("字符串中有空格");
e.printStackTrace();
break;
}
}
}
}本回答被提问者采纳
第3个回答  2012-05-11
import java.util.Scanner;

public class Str {

/**
* @param args
*/
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while (in.hasNext()) {
String s=in.nextLine();
if (s.contains(" ")) {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("the string contains space");
e.printStackTrace();
}
}

}

}

}
相似回答