简体   繁体   English

将输入扫描到char数组Java中

[英]Scanning input into char array Java

I was trying to store input as 我试图将输入存储为

5 
3DRP 3QEW
8AQW 9ADA

I want to read that input in as a copy paste and put it. 我想将输入内容复制粘贴并放入。 I've tried this: 我已经试过了:

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    String userNumber;
    userNumber = scan.nextLine();
    String[] tokens = userNumber.split("[ ]");
    System.out.println(tokens[1]);
    for(int i = 0; i < tokens.length;i++) {
        System.out.println(tokens[i]);
    }
    scan.close();
}

My goal is to basically read that input in as a copy paste into the IDE or through a file a .txt and then store every single character besides whitespaces into a char array that is 1d or 2d. 我的目标是基本上将输入内容复制粘贴到IDE中,或通过.txt文件读取,然后将除空格以外的每个单个字符存储到1d或2d的char数组中。

From what I understand, you want to read 3 lines from the console, remove all the white spaces from that text and store it as a char array. 据我了解,您想从控制台读取3行,删除该文本中的所有空白并将其存储为char数组。

If that is the case, here is how you could do that: 如果是这种情况,请按照以下步骤操作:

    int numberOfLinesToRead = 3;
    try(Scanner sc = new Scanner(System.in)){
        StringBuilder buff = new StringBuilder();
        while(numberOfLinesToRead-- > 0){
            String line = sc.nextLine();
            String noSpaces = line.replaceAll("\\s", "");
            buff.append(noSpaces);
        }
        char[] characters = buff.toString().toCharArray();
        System.out.println(Arrays.toString(characters));
    }catch (Exception e) {
        e.printStackTrace();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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