【问题标题】:Java read elements in string element by elementJava逐个元素读取字符串中的元素
【发布时间】:2014-02-17 18:18:08
【问题描述】:

好的,我在从字符串中读取元素时遇到了一些问题,我得到了一些用户输入的文件,并且我将每一行都读入了一个数组列表。现在我需要访问每一行并从中读取这些整数并将它们设置为 int 变量。尽管参见下面的示例,但每行将有多个整数。有人可以帮忙吗?

1 5
1 4
2 3
3 1
10 13
100 203
etc...

所以对于第一行,我想做类似的事情:

first line:
int i = string.element1 // 1
int j = string.element2 // 5

...etc...

last line:
int i = string.element1 // 100
int j = string.element2 // 203

【问题讨论】:

    标签: java string arraylist


    【解决方案1】:

    尝试使用split()方法获取Strings,然后通过parseInt()将其转换为int

    int i = 0, j = 0;
    String string = "100 203";
    String[] parts = string.split(" ");
    
    i = Integer.parseInt(parts[0]);
    j = Integer.parseInt(parts[1]);
    

    【讨论】:

      【解决方案2】:
      ArrayList<String> yourArray...; //this is your array list containing all lines from your file
      for(String data : yourArray){
          String[] nums = data.split(" ");
          Integer num1 = Integer.parseInt(nums[0]);
          Integer num2 = Integer.parseInt(nums[1]);
      }
      

      类似的东西?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多