2017-08-10 26 views
0

我有以下代码:更换特定号码 - For循环

List<String> l1_0 = new ArrayList<String>(), l2_0 = new ArrayList<String>(),.....; 
List<Integer> l1_1 = new ArrayList<Integer>(), l2_1 = new ArrayList<Integer>()......; 
int lines1 = 0, lines2 = 0, lines3 = 0 .....; 

     Scanner s1 = new Scanner(new FileReader("file/path//t1.txt")); 


    while (s1.hasNext()) { 
     l1_0.add(s1.next()); 
     l1_1.add(s1.nextInt()); 
     lines1++; 
    } 
    s1.close(); 

    func1(l1_0,l1_1,lines); 

我必须为40个文件执行相同的操作。

我们可以创建一个for循环来实现它吗? 我正在考虑沿线的东西。

for (int i=1; i<= 40 ; i++) 
{ 
    Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt")); 
    while (s[i].hasNext()) { 
     l[i]_0.add(s[i].next()); 
     l[i]_1.add(s[i].nextInt()); 
     lines[i]++; 
    } 
    s[i].close(); 
    func1(l[i]_0,l[i]_1,lines[i]); 
} 
+1

是的,你可以使用一个循环。 [为什么“有人可以帮助我?”不是一个真正的问题?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question ) – tnw

+1

请注意,数组是**零索引**,并且不需要扫描程序数组 –

+0

作为新的Java程序员,您应该遵循以下Java约定,包括命名变量。它应该是'file1Lines'或类似的,而不是'l1_0'。 (例如,没有蛇的情况下,描述性的名字等) –

回答

1

如果我理解正确,您希望循环数据40次。每个文件一次。

for (int i=0; i< 40 ; i++) 
{ 
    // Initializers for this one file 
    List<String> strings = new ArrayList<>(); 
    List<Integer> nums = new ArrayList<>(); 
    int lineCount = 0; 

    String filename = "t" + i; 

    try (Scanner s = new Scanner(new FileReader("file/path/" + filename + ".txt"))) { 

     while (s.hasNext()) { 
      strings.add(s.next()); 
      if (s.hasNextInt()) { 
       nums.add(s.nextInt()); 
      } 
      lineCount++; 
     } 
    } 

    func1(strings,nums,lineCount); 
} 
+1

由于用户是Java的新用户,因此我建议通过try/finally或try-with-resources关闭输入流来展示最佳实践。 –

+0

谢谢@ cricket_007 ..它工作:)我意识到这是一个愚蠢的问题! – Chid

0
for (int i=1; i<= 40 ; i++){ 
    Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt")); 
} 

在java中没有隐含String图案分辨率。这意味着你必须创建自己,String表示这种新的文件名:

"file/path//t" + i + ".txt" 

或者你可以使用String.format()

String.format("file/path//t%d.txt",i) 
+0

感谢您的帮助:) – Chid