[英]Read in number file and calculate average in java
我有一個名為“ averages”的txtfile,看起來像:
1 4 5 3 -1
2 8 9 3 2 -1
4 8 15 16 23 42 -1
3 -1
我希望能夠讀取每一行並計算每當達到“ -1”時的每一行的平均值。 我已經編寫了讀取文件中的代碼並將其打印到命令行的代碼,但是我很難找到每一行的平均值。 任何幫助將不勝感激。 謝謝!
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("averages.txt"));
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine);
}
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (reader != null)reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
您可以執行以下操作:
使用split方法分割currentLine
:
String[] nums = currnetLine.split("\\\\s+");
循環遍歷nums
並將每個元素解析為int
然后將其添加到sum
變量
int sum = 0; for (int i = 0; i < nums.length; i++) { int num = Integer.parseInt(nums[i]); if(num != -1) { sum += num; } }
最后計算平均值。
sum/(nums.length - 1);// -1 because you need to execlude the -1 at the end of your line
我會嘗試這樣的事情:
int sum = 0;
String[] values = currentLine.split(" ");
for (String value : values) {
int n = Integer.parseInt(value);
if (n < 0) {
break;
}
sum += n;
}
int count = values.length - 1;
// calculate average from sum and count
在Java 7+中,“掃描程序”對象可用,並且具有各種有用的功能。
1.)首先讀入Scanner掃描器= new Scanner(“ 1 51 2 52”);
2)從上面的代碼中,如果您有一個空格定界符,則可以很容易地使用scan.useDelimiter(“”);
3.)如果為scanner.hasNext(),則為下一個字符串使用scanner.next()。
使用Integer.parseInt(“ 1”)迭代列表以獲取值,總和,然后取平均值。
請嘗試以下方法:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("averages.txt"));
while ((currentLine = reader.readLine()) != null) {
System.out.println(currentLine);
StringTokenizer st=new StringTokenizer(currentLine," ");
int count=st.countTokens();
int array[]=new int[count-1];
int i=0;
while(st.hasMoreTokens()&&i!=count-1)
{
array[i]=Integer.valueOf(st.nextToken());
i=i+1;
}
int sum=0;
for(int x=0;x<array.length;x++)
{
sum=sum+array[x];
}
float average=(float)sum/array.length;
System.out.println("The average of this line is: "+average);
}
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (reader != null)reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
我的邏輯是,您一次讀取一行,並用空格隔開。 然后,將這些分隔的字符串轉換為Integer。 最后一步是將它們加起來並做一些數學運算以獲得平均值。
希望這可以幫助。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.