[英]How do I filter a user input to accept char and int, but not specialchar. Then only takes the int into an array
Create a new queue with the String data type, wherein the user inputs the elements of the queue.使用 String 数据类型创建一个新队列,其中用户输入队列的元素。
Restrictions:限制:
This is the requirement for the program.这是程序的要求。 And this is what I have so far:
这就是我到目前为止所拥有的:
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);
}
}
Obviously this program only removes char without being combined with int.显然这个程序只删除了 char 而没有与 int 结合。 I tried to use the
replaceAll("[^\\d]", " ");
我尝试使用
replaceAll("[^\\d]", " ");
but I don't know how to make it work.但我不知道如何使它工作。 Please help.
请帮忙。
The characters you allow are AZ
, az
, and 0-9
.您允许的字符是
AZ
、 az
和0-9
。 In a regular expression \\w
matches those characters.在正则表达式中,
\\w
匹配这些字符。 And \\W
matches any but those characters.并且
\\W
匹配除这些字符之外的任何字符。 So set the latter to your delimiter and see how it works.所以将后者设置为你的分隔符,看看它是如何工作的。
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\W+");
while (true) {
System.out.println(scan.next());
}
Each group of characters returned from scan.next()
should only contain your allowable characters.从
scan.next()
返回的每组字符应该只包含您允许的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.