文本文件(myfile.txt)的编号如下:
6
19
20
23
34
45
47
51
54
56
61
70
72
76
90
93
94
96
105
111
我可以用Java读取和打印这个文本文件作为字符串标记,我的代码是:
File fileName = new File("myfile.txt");
Scanner inFile = new Scanner(fileName);
while (inFile.hasNext())
{
token = inFile.next( );
System.out.println(token);
}
inFile.close();
现在如何在java中获取这些数字的总和?我的意思是SUM(6 + 19 + 20 + 23 + .......... + 111)
答案 0 :(得分:3)
使用 int 变量 sum ,并使用scanner.nextInt()
提取数字。并在每次迭代时进行添加。
File fileName = new File("myfile.txt");
Scanner inFile = new Scanner(fileName);
int sum=0;
while (inFile.hasNext())
{
sum+= inFile.nextInt( );
}
System.out.println(sum);
inFile.close();
答案 1 :(得分:1)
您可以使用Integer.parseInt
方法将字符串转换为int。然后将其添加到您需要在外面声明的sum
变量。
Scanner inFile = new Scanner(fileName);
int sum = 0;
while (inFile.hasNext()) {
token = inFile.next( );
System.out.println(token);
sum += Integer.parseInt(token);
}
好吧,如果你正在读取整数值,使用inFile.nextInt()
是一个更好的选择。并在while循环中使用inFile.hasNextInt()
。
答案 2 :(得分:0)
首先使用nextInt()
类的Scanner
将整数读入List
。然后使用“增强型”for
循环
答案 3 :(得分:0)
所以我能够弄清楚我的问题并且很成功,但我仍然希望任何人都可以通过使用teranary运算符来简化这种语法。
import java.util.Scanner;
import java.io.*;
public class Midterm
{
public static void main(String[]args) throws Exception
{
final String FILE = "integers.txt";
final String RELATIVE_DIRECTORY_FILE = "integers.txt ";
int positiveNumberCount = 0,
negativeNumberCount = 0;
String dataItem;
double sum = 0;
double sumForAverage = 0;
double average = 0;
File inputFile = new File(RELATIVE_DIRECTORY_FILE);
if(!inputFile.exists())
{
System.out.printf("%n%s%s%s", "The file, ", RELATIVE_DIRECTORY_FILE, " does not exist");
}
if(inputFile.exists())
{
System.out.printf("%s%s%s", "The file ", RELATIVE_DIRECTORY_FILE, "was found");
Scanner file = new Scanner(inputFile);
//***if i need to use a delimiter *****
//file.useDelimiter(",") where in between " " is my type of delimiter
while(file.hasNext())
{
dataItem = file.nextLine();
double numericalDataItem = Double.parseDouble(dataItem);
boolean isPositive = false;
boolean isNegative = false;
if(numericalDataItem > 0)
{
isPositive = true;
positiveNumberCount++;
}
else if(numericalDataItem < 0)
{
isNegative = true;
negativeNumberCount++;
}
sum += Double.parseDouble(dataItem);
sumForAverage = positiveNumberCount + negativeNumberCount;
average = sum/sumForAverage;
}
System.out.printf("%n%s%d%n%s%d%n%s%.2f%n%s%.2f", "Positive Number Count: ", positiveNumberCount,
"Negative Number Count: ", negativeNumberCount, "Sum Of Numbers: ", sum, "Average of Numbers: ", average);
}
}
}