简体   繁体   English

从 String[] Java 解析整数对

[英]Parsing pairs of integers from String[] Java

How would I go about parsing pairs of integers after the first string in a string array.我将如何在字符串数组中的第一个字符串之后解析整数对。 In my while loop below, i've assigned the letter 'A','B','C', but now I'm trying to assign pairs of numbers to a class input eg.在下面的 while 循环中,我已经分配了字母“A”、“B”、“C”,但现在我正在尝试将数字对分配给类输入,例如。 class X(int i, int j), does anyone have any tips of what to do from here? class X(int i, int j),有没有人有任何关于从这里做什么的提示?

An example input would be : 
A 32 12 34 12 
B 12 22 11 11
C 1  4   1  2

 public static void readFile(String f) throws IOException {
            BufferedReader in = new BufferedReader(new FileReader(f));
            String line;
            String[] str;
            Scanner s;
            try {

                line = in.readLine();
                s = new Scanner(line);
                int number = s.nextInt();
                if (s.hasNextInt()) {
                    number = s.nextInt(); 
                } 
                s.close();
                line = in.readLine(); 
                numLines = Integer.parseInt(line);

                while((line = input.readLine())!=null){
                      String[] pair = line.split(" ");
                      String letter;        
                      letter = pair[0];
                  }

                if (!numLines.equals(lineCount)) { 
                System.exit(0);
                }           
            } catch (Exception e) {
            } finally {
                in.close(); 
            }
        }

You need to split the line and then parse individual numbers.您需要拆分该行,然后解析单个数字。

Something like this:像这样的东西:

String[] a = {"A 32 12 34 12","B 12 22 11 11", "C 1  4   1  2"};
    
for (String s: a) {
    String[] line = s.split("\\s+");
    
    for (int i = 1; i < line.length; i++) {
        System.out.print(Integer.parseInt(line[i]) + " ");
    }
    System.out.println();
}

Output:输出:

32 12 34 12 32 12 34 12

12 22 11 11 12 22 11 11

1 4 1 2 1 4 1 2

For the sake of example, I am using array to show how it works.举例来说,我使用数组来展示它是如何工作的。 You can make changes based on your requirements.您可以根据自己的要求进行更改。 You note in question something about class x(...) but nothing in your code shows that so I won't bother to show something that I don't understand.您注意到有关class x(...)一些问题,但您的代码中没有任何内容表明这一点,因此我不会费心展示我不理解的内容。

Demo演示

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

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