【问题标题】:Multitask: parse space-separated integers from a string多任务:从字符串中解析空格分隔的整数
【发布时间】:2014-10-31 08:28:50
【问题描述】:

我的任务有问题。

我的工作是

  • 从文件中获取String(在源文件中是一行中的数字,除以空格)
  • 用空格分割字符串
  • 然后将每个String 解析为int
  • 最后对它们使用bubbleSort。

我一直在解析,不知道该怎么做。

代码 atm 看起来像这样:

public class Main
{
    public static void main(String[] args) throws IOException
    {
        String numbers = new String(Files.readAllBytes(Paths.get("C:\\README.txt")));
        String s[] = numbers.split(" ");
        for (String element : s)
        {
           System.out.println(element);
        }
    }
}

我尝试使用扫描仪读取字符串数字,然后将其循环用于 parseInt,但对我不起作用。

【问题讨论】:

  • 您在尝试 parseInt 时遇到任何错误吗?请详细说明您的问题:)

标签: java string parsing split int


【解决方案1】:

你要找的方法是Integer#parseInt()

当使用 Java 8 时,您可以使用Stream API,如下所示:

final List<Integer> intList = new LinkedList<>();

try {
    Files.lines(Paths.get("path\\to\\yourFile.txt"))
        .map(line -> line.split(" "))
        .flatMap(Stream::of)
        .map(Integer::parseInt)
        .forEach(intList::add);
} catch (IOException ex) {
    ex.printStackTrace();
}

没有流:

final List<Integer> intList = new LinkedList<>();

try {
    for (String line : Files.readAllLines(Paths.get("path\\to\\yourFile.txt"))) {
        for (String numberLiteral : line.split(" ")) {
            intList.add(Integer.parseInt(numberLiteral));
        }
    }
} catch (IOException ex) {
    ex.printStackTrace();
}

【讨论】:

    【解决方案2】:

    你可以试试这个:

      public class Main
      {
          public static void main(String[] args) throws IOException
          {
              String numbers = new String(Files.readAllBytes(Paths.get("C:\\README.txt")));
              String s[] = numbers.split(" ");
              for (String element : s)
              {
                 int number = Integer.valueOf(element)  // transform String to int 
                 System.out.println(number);
              }
          }
      } 
    

    我认为一个想法是将整个 String-Array 转换为 int-arrayList of Integers

    这可以做到,用这个方法(几乎和上面一样):

      private List<Integer> transformToInteger(final String[] s) {
          final List<Integer> result = new ArrayList<Integer>();
          for (String element : s)
          {
            final int number = Integer.valueOf(element);
            result.add(number);
          }
          return result;
        }
    

    现在您可以对这个结果列表执行冒泡排序了。

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      • 2019-12-04
      • 2012-04-25
      • 2019-06-14
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多