从 Java 中的文件中读取并计算整数总和
Read and calculate sum of integers from a file in Java
假设我有一个简单的文本文件Simple.txt,其中包含这样的数据
1 2 3 4 5 6
或
1
2
3
4
5
如何读取此文件并使用 Java 打印整数之和?
试试这个。
import java.util.*;
import java.io.File;
import java.io.IOException;
public class ReadFile
{
public static void main(String[] args)
throws IOException
{
Scanner textfile = new Scanner(new File("Simple.txt"));
filereader(textfile);
}
static void filereader(Scanner textfile)
{
int i = 0;
int sum = 0;
while(textfile.hasNextLine())
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
试试这个代码。
import java.io.*;
import java.util.*;
public class SumNumbers {
public static void main(String args[]){
try{
File f = new File(args[0]);
Scanner scanner = new Scanner(f);
int sum = 0;
while (scanner.hasNext()){
sum += scanner.nextInt();
}
System.out.println("Sum:"+sum);
}catch(Exception err){
err.printStackTrace();
}
}
}
编辑:如果你想在文件中捕获不正确的输入,你可以改变 while 循环如下
while (scanner.hasNext()){
int num = 0;
try{
num = Integer.parseInt(scanner.nextLine());
}catch(NumberFormatException ne){
}
sum += num;
}
假设我有一个简单的文本文件Simple.txt,其中包含这样的数据
1 2 3 4 5 6
或
1 2 3 4 5
如何读取此文件并使用 Java 打印整数之和?
试试这个。
import java.util.*;
import java.io.File;
import java.io.IOException;
public class ReadFile
{
public static void main(String[] args)
throws IOException
{
Scanner textfile = new Scanner(new File("Simple.txt"));
filereader(textfile);
}
static void filereader(Scanner textfile)
{
int i = 0;
int sum = 0;
while(textfile.hasNextLine())
{
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum = sum + nextInt;
i++;
}
}
试试这个代码。
import java.io.*;
import java.util.*;
public class SumNumbers {
public static void main(String args[]){
try{
File f = new File(args[0]);
Scanner scanner = new Scanner(f);
int sum = 0;
while (scanner.hasNext()){
sum += scanner.nextInt();
}
System.out.println("Sum:"+sum);
}catch(Exception err){
err.printStackTrace();
}
}
}
编辑:如果你想在文件中捕获不正确的输入,你可以改变 while 循环如下
while (scanner.hasNext()){
int num = 0;
try{
num = Integer.parseInt(scanner.nextLine());
}catch(NumberFormatException ne){
}
sum += num;
}