简体   繁体   English

如何过滤用户输入以接受 char 和 int,但不接受 specialchar。 然后只将 int 放入一个数组中

[英]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:限制:

  1. The user can only input letters and numbers (AZ, az & 0-9)用户只能输入字母和数字(AZ、az & 0-9)
  2. The program only takes the numbers from the input (integer)该程序仅从输入中获取数字(整数)
  3. In any instance that at least one special character is entered, the program will return an error.在输入至少一个特殊字符的任何情况下,程序将返回错误。 (this includes SPACE) (这包括空间)

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 .您允许的字符是AZaz0-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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM