2013-07-13 25 views
-4

你好傢伙我有一個問題,試圖把第一行放入10個整數的數組中。以下是我迄今爲止如何讀取文件的第一行並將它們存儲在java中的數組中?

public class KnapEncrypt { 

public static void main(String[] args) throws FileNotFoundException { 
    File file = new File("Testinput.txt"); 
    Scanner sc = new Scanner(file); 

    while(sc.hasNext()){ 
    int line = sc.nextInt(); 
    System.out.println(line); 
    } 



} 
} 

這是文件:

191 691 573 337 365 730 651 493 177 354 

1000011100 

1101000001 

0000100010 

0100000000 

1028 

2426 

2766 

1129 

Basicaly什麼,我要的是把第一行到一個數組中包括10個整數但數字

的不是休息
+0

把前十個你進入一個數組而忽略其他。 –

+0

你的陣列在哪裏?你需要一個把東西存儲在一個數組中。閱讀有關數組的Java教程:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html –

+0

這看起來是'java scanner first line'的頂級谷歌結果,它引出了爲什麼它是關閉/關閉的話題。 – hamitron

回答

2
FileInputStream fis = new FileInputStream("your_file_here"); 

    Scanner scanner = new Scanner(fis); 
    String firstLine = scanner.nextLine(); 

    firstLine.trim(); 
    String[] data = firstLine.split(" "); 

    int[] intData = new int[data.length]; 

    for (int i = 0; i < intData.length; i++) { 
     intData[i] = Integer.parseInt(data[i]); 
    } 
3
BufferedReader reader = new BufferedReader(new FileInputStream(file)); 
String line = reader.readLine(); 
String[] lineSplitted = line.split(" "); 
2

首先閱讀您的線路從文件:

String line = bufferedReaderForFile.readLine(); 

然後用手給你的scanner

Scanner sc = new Scanner(line); 
// your while loop here 
相關問題