2014-10-31 67 views
0

我遇到任務問題。多任務:從字符串中解析空格分隔的整數

我的工作是

  • 抓鬥從文件中String(在源文件是數字在一行中,由空間劃分)
  • 分裂由空格該字符串
  • 然後分析每個Stringint
  • 最後在它們上面使用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函數,但對我不起作用。

+3

你有沒有試圖parseInt得到任何錯誤?請詳細說明你的問題:) – Frunk 2014-10-31 08:31:33

回答

0

你可以試試這個:

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; 
    } 

現在你可以在這個結果列表上執行你的氣泡排序。

2

你正在尋找的方法是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(); 
}