[英]asking for user String input without spaces in java
如果用戶輸入帶空格的字符串,我需要程序返回一條消息。 例如,不允許使用“這是我的房子”,而允許使用“ thisismyhouse”。 現在我用這段代碼檢查空格
for(int i = 0; i < blabla.length(); i++) {
if (blabla.charAt(i) == ' ')
flag++;
}
}
if (flag != 0) {
System.out.println("input must not contain spaces");
}
我想知道是否為此目的有諸如blabla.equals之類的內置函數? 還是寫這個更好的方法?
解決方案1:
if(input.contains(" "))
System.out.println("input must not contain spaces");
解決方案2:
if(input.indexOf(" ")>=0)
System.out.println("input must not contain spaces");
解決方案3:
您可以簡單地允許用戶輸入空格並自行刪除它們:
input = input.replaceAll(" ","");
嘗試
if (blabla != null && blabla.contains (" ")) {
System.out.println("input must not contain spaces");
return;
}
這應該可以解決問題。
if(blabla.contains(" ")){};
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#contains(java.lang.CharSequence)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.