[英]How do I filter a user input to accept char and int, but not specialchar. Then only takes the int into an array
使用 String 數據類型創建一個新隊列,其中用戶輸入隊列的元素。
限制:
這是程序的要求。 這就是我到目前為止所擁有的:
import java.util.Queue;
import java.util.Scanner;
import java.util.Iterator;
public class Main {
public static void main (String args[]){
Scanner scan = new Scanner(System.in);
System.out.println("This is a Queue program. Please enter how many integer/s will be inputted.");
int count = scan.nextInt();
scan.nextLine();
System.out.println("Enter the valid interger/s:");
String[] list = new String[count];
for (int i = 0; i < count; i++){
list[i] = scan.nextLine();
}
Queue<String> newlist = new LinkedList<>();
for (String i:list){
newlist.add(i);
}
System.out.println(newlist);
Iterator<String> i=newlist.iterator();
while(i.hasNext()){
if(i.next().toString().matches("[^0-9]+")){
i.remove();
}
}
System.out.println(newlist);
}
}
顯然這個程序只刪除了 char 而沒有與 int 結合。 我嘗試使用replaceAll("[^\\d]", " ");
但我不知道如何使它工作。 請幫忙。
您允許的字符是AZ
、 az
和0-9
。 在正則表達式中, \\w
匹配這些字符。 並且\\W
匹配除這些字符之外的任何字符。 所以將后者設置為你的分隔符,看看它是如何工作的。
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\W+");
while (true) {
System.out.println(scan.next());
}
從scan.next()
返回的每組字符應該只包含您允許的字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.