简体   繁体   中英

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.

Restrictions:

  1. The user can only input letters and numbers (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. I tried to use the replaceAll("[^\\d]", " "); but I don't know how to make it work. Please help.

The characters you allow are AZ , az , and 0-9 . In a regular expression \\w matches those characters. And \\W matches any but those characters. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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