2013-12-15 74 views
-3

我正在嘗試讀取和寫入文件。從txtfile獲取值並將其放入數組

我有兩個txt文件

input.txt中:

4 
    1 1 
    2 2 
    3 2 
    3 3 
    2 3 

和output.txt的我想從inputx.txt獲得價值就像一個

4 //is first value 
int[] x = {1,2,3,3,2} 
int[] y = {1,2,2,3,3} 

如何解析它?

+6

詢問代碼的問題必須顯示對所解決問題的最小理解**。包括嘗試解決方案,爲什麼他們沒有工作,以及預期的結果。另請參見:[堆棧溢出問題清單](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) – johnchen902

回答

0

這裏是一個示例代碼,它不是最好的方法,但只是給你一個關於如何去做的提示。

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 
public class Test { 

    public static void main(String[] args) throws FileNotFoundException{ 
     String filename = "text.txt"; 
     Scanner sc = new Scanner(new File(filename)); 
     String s; 
     int i = 0; 
     int firstVal = 0; 
     ArrayList<Integer>x=new ArrayList<Integer>(); 
     ArrayList<Integer>y=new ArrayList<Integer>(); 
     while(sc.hasNext()){ 
      s=sc.next(); 
      if(s.trim().isEmpty()) 
       continue; 
      if(i<1){ 
       firstVal = Integer.valueOf(s).intValue(); 
      }else{ 
       if(i%2 > 0){ 
        x.add(Integer.valueOf(s)); 
       }else{ 
        y.add(Integer.valueOf(s)); 
       } 
      } 
      i++; 
     } 
     for(int xv: x){ 
      System.out.println(xv); 
     } 
     System.out.println("-----------------"); 
     for(int yv: y){ 
      System.out.println(yv); 
     } 
    } 
} 
相關問題