2017-11-03 3 views

答えて

0

そのためのすべての重複投稿(引用されているとのものは)私はそれを達成するための簡単な方法(と、より最近の)示唆し、少し古いですので:

public static int method1(String path) throws IOException { 
    int sum = 0; 
    for (String line : Files.readAllLines(Paths.get(path))) 
     sum += Integer.parseInt(line); 
    return sum; 
} 

public static int method2(String path) throws IOException { 
    return Files.readAllLines(Paths.get(path)).stream().mapToInt(Integer::parseInt).sum(); 
} 

Files.readAllLines(somePath)はそうList<String>返しますfrstメソッドは、古典的なfor each loopparse to Integerと合計で繰り返します。使用するには(反復と同じこと)


Streams::第二の方法は、Java 8の最新のAPIを使用して、別の構文を使用して同じことをするでしょう

public static void main(String[] args) throws IOException { 
    System.out.println(method1("numbs.txt")); // if file is not in same folder 
    System.out.println(method2("numbs.txt")); //use absolute path: C:\users\...\numbs.txt 
} 
+0

Hmh ..まあまあ^^ – Noixes

関連する問題