[英]How to read a .txt file for each int on a line & storing to array?
public class assignment2
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
FileInputStream fstream = new FileInputStream("assignment2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
String[] numbers = strLine.split(" ");
System.out.print(numbers[1]);
}
//Close the input stream
br.close();
}
}
我希望代碼將String []數字打印為1 0 10
我得到這個結果00371010
請注意,輸入文件的格式如下:
1 0 10
2 0 9
3 3 5
4 7 4
5 10 6
6 10 7
只需替換您的行:
System.out.print(numbers[1]);
附:
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
System.out.println();
讓我知道它是如何工作的。
您需要通過添加另一個循環來修改代碼,如下所示:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream fstream = new FileInputStream("assignment2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null){
// Print the content on the console
System.out.println (strLine);
String[] numbers = strLine.split(" ");
for (String num : numbers){
System.out.print(num + " ");
}
System.out.println("\n");
}
//Close the input stream
br.close();
}
因為,numbers [1]僅將索引1上的值打印出來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.