I have a txtfile called "averages" that looks like:
1 4 5 3 -1
2 8 9 3 2 -1
4 8 15 16 23 42 -1
3 -1
I want to be able to read in each line and calculate the average of each line whenever a "-1" is reached. I have written the code to read in the file and print it to the command line, I'm just having trouble finding the averages of each line. Any help would be greatly appreciated. Thanks!
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();
}
}
}
}
You could do it by doing the following:
split the currentLine using split method:
String[] nums = currnetLine.split("\\s+");
loop over the nums and parse each elements to int then add it to a
sum variable
int sum = 0;
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if(num != -1) {
sum += num;
}
}
Finally calculate the average.
sum/(nums.length - 1);// -1 because you need to execlude the -1 at the end of your line
I'd try something like this:
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
In Java 7+, the Scanner object is available and has a variety of useful functions to use.
1.) First read in the line
Scanner scanner = new Scanner("1 51 2 52");
2.) From your code above, if you have a space delimiter, it is easy to work with
scanner.useDelimiter(" ");
3.) If scanner.hasNext() then scanner.next() for the next string.
Iterate the list using Integer.parseInt("1") to get the value, sum, then average.
Please try this:
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();
}
}
}
}
My logic is that you read a line at a time and separate them by spaces. Then you convert those separated string into Integer. Last step is add them up and do some math to get the average.
Hope this helps. Thanks!
Related
Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.
For example (the txt file would contain the following numbers)
4567687509
569563
the marks are:
45%, 67%, 68%, 75%, 9%
56%, 95%, 63%
Write a method that will calculate the average of each set of marks as well as the overall average.
Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.
import java.io.*;
public class ReadFile {
public static int calcAvg (String x) throws IOException {
int avg = 0;
int count = 0;
FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
BufferedReader br = new BufferedReader (fr);
while ((x = br.readLine()) != null) {
if (count <= 2) {
}
}
br.close();
return avg;
}
considering an input file like
45676875
09569563
first I will have a method to read the file and transform it into a better structure to use.
public List<Integer> readFile() throws FileNotFoundException {
List<Integer> numbers = new ArrayList<>();
String line = "";
try {
FileReader fr = new FileReader("src/main/resources/numbers.txt");
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
for (int i = 0; i <= line.length() - 2; i+=2) {
char[] chars = line.toCharArray();
int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
numbers.add(number);
}
}
} catch (Exception e) {
System.out.println(e);
}
return numbers;
}
then I will have the method to calculate the AVG
public float calcAvg(List<Integer> numbers) throws IOException {
int sum = 0;
for (int number: numbers){
sum+= number;
}
return sum/(numbers.size());
}
of course, you need a start method to make things happen
something like
public void init() throws IOException {
List<Integer> numbers = readFile();
float result = calcAvg(numbers);
System.out.println(result);
}
It's as easy as that. You practically want people to do stuff for you, but this is a question and answer site. Here you'll see some code for getting the individual percentages. You'll figure the rest out.
File f = new File(path);
try {
Scanner scanner = new Scanner(f);
String line = scanner.nextLine();
for (int i = 0; i < line.length() - 1; i+=2) {
double percentage = Double.parseDouble(line.substring(i, i+2)) / 100.0;
}
} catch (Exception e) {e.printStackTrace();}
I have a task to read a text file with several lines, after that I need to count every character's UNICODE value, so the sum of "hello" is 532 and for "how are you" is 1059 and so on, every string begins on new line in the .txt document and so far so good.
But for every line I need to print only its own value, and the way my code works, it adds every line's value and I cant get my head around a way to stop it when the end of the lxtine comes so it looks something like:
*read line
*count char values
*add up
*print them
*start over for the next line, and so
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.String;
import java.util.Arrays;
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int sum = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
char[] array = new char[readLine.length()];
System.out.println(readLine);
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
sum += (int) array[i];
System.out.print(sum + " ");
}
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + sum);
}
}
If I understood correctly, for the input:
hello
how are you
You would like to get something like this as output:
hello 532
how are you 1059
*** final 1591
For this, you need to make some modifications to your code:
In addition to calculating the sum of characters values per line, keep another sum of the total of all lines
For each input line, print the line followed by the sum of character values
You don't need an array at all
It's better to trim the input line once, instead of for every character
Like this:
int total = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
String trimmed = readLine.trim();
int sum = 0;
for (int i = 0; i < trimmed.length(); i++) {
sum += (int) trimmed.charAt(i);
}
System.out.println(readLine + " " + sum);
total += sum;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + total);
After your for loop, set sum to 0. If you want to print the total sum, then you need another variable, say t.
Like this:
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
sum += (int) array[i];
System.out.print(sum + " ");
}
t=t+sum;
sum=0;
Then print t at the end.
A simple solution would be to limit the scope of the sum variable. That way, values will not persist between runs:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.String;
import java.util.Arrays;
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int totalSum = 0;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
String readLine;
while ((readLine = bufferedReader.readLine()) != null) {
int sum = 0;
for (int i = 0; i < readLine.length(); i++) {
sum += (int) readLine.charAt(i);
}
System.out.println(readLine + ": " + sum);
totalSum += sum;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + totalSum);
}
}
Also, you don't have to use such complicated stuff just to get the Unicode value of a char. I made some improvements.
Have two variables, one for final sum and one for line sum.
public class SumLines {
public static void main(String[] args) {
String filePath = "/home/lines.txt";
String readLine;
int totalSum = 0;
int lineSum = 0
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
char[] array = new char[readLine.length()];
System.out.println(readLine);
for (int i = 0; i < readLine.length(); i++) {
Arrays.fill(array, readLine.trim().charAt(i));
lineSum += (int) array[i];
System.out.print(lineSum + " ");
}
totalSum += lineSum + totalSum;
lineSum = 0;
}
} catch (IOException e) {
System.out.println("Error.\n Invalid or missing file.");
e.printStackTrace();
}
System.out.println("\n*** final " + totalSum);
}
}
I have been given this question for practice and am kind of stuck on how to complete it. It basically asks us to create a program which uses a BufferedReader object to read values(55, 96, 88, 32) given in a txt file (say "s.txt") and then return the smallest value of the given values.
So far I have got two parts of the program but i'm not sure how to join them together.
import java.io.*;
class CalculateMin
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
int numberOfLines = 5;
String[] textInfo = new String[numberOfLines];
for (int i = 0; i < numberOfLines; i++) {
textInfo[i] = br.readLine();
}
br.close();
} catch (IOException ie) {
}
}
}
and then I have the loop which I made but i'm not sure how to implement it into the program above. Eugh I know i'm complicating things.
int[] numArray;
numArray = new int[Integer.parseInt(br.readLine())];
int smallestSoFar = numArray[0];
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] < smallestSoFar) {
smallestSoFar = numArray[i];
}
}
Appreciate your help
Try this code, it iterates through the entire file comparing number from each line with the previously read lowest number-
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("grades.txt"));
String line;
int lowestNumber = Integer.MAX_VALUE;
int number;
while ((line = br.readLine()) != null) {
try {
number = Integer.parseInt(line);
lowestNumber = number < lowestNumber ? number : lowestNumber;
} catch (NumberFormatException ex) {
// print the error saying that the line does not contain a number
}
}
br.close();
System.out.println("Lowest number is " + lowestNumber);
} catch (IOException ie) {
// print the exception
}
}
I'm trying to read a text file called input.in an array of characters representing a map. The file contains two integers N and numLifes, and the corresponding matrix. N represents the dimension of a square matrix (NxN).
I want that if N is less than 10, assign to the variable N, the value of 10 and fill the matrix 'mVill' with a '#', and then read the map file and integrate it with the matrix filled with '#'. Heres the code:
import java.io.*;
import java.io.FileReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class hola {
public static void main(String[] args) {
char mVill[][] = null;
int N, i,j, numLifes;
String line=null;
StringTokenizer tk;
char caract;
FileInputStream fstream = null;
try {
fstream = new FileInputStream("C:/input.in");
} catch (FileNotFoundException e) {
System.exit(-1);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
try {
if ((line = br.readLine()) == null) {
System.out.print("Error empty file...");
System.exit(0);
}
} catch (IOException e) {
}
tk = new StringTokenizer(line);
N = Integer.parseInt(tk.nextToken());
numLifes = Integer.parseInt(tk.nextToken());
int nAux=N;
if (N<10){
N=10;
mVill = new char[N][N];
for (char[] row: mVill)
Arrays.fill(row, '#');
for (i=0; i <nAux; i++) {
for (j=0;j<nAux;j++){
try{
caract = (char) br.read();
mVill[i][j]=caract;
}catch (Exception e){
System.out.println("Error in read file");
}
}
}
}else{
mVill = new char[N][N];
for (i = 0; i < N; i++) {
try {
mVill[i] = br.readLine().toCharArray();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
System.out.println(N+" "+numLifes);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
System.out.print(mVill[i][j]);
}
System.out.println();
}
}//end main
}//end class
For this input:
7 3
F..*..F
.##.##.
.#...#.
*..P..*
.#...#.
.##.##.
F..*..F
the output is (which is wrong):
F..*..F###
.##.####
#.
.#.###
..#.
*###
..P..*
###
.#...####
.
.##.###
##########
##########
##########
The output should I expect to receive it:
F..*..F###
.##.##.###
.#...#.###
*..P..*###
.#...#.###
.##.##.###
F..*..F###
##########
##########
##########
What am I doing wrong? I do not see any error in reading the file.
Following Steve's answer, the quick and dirty way to correct it would be to do this when you are reading your characters:
caract = (char) br.read();
while (caract == '\n' || caract == '\r') {
caract = (char) br.read();
}
mVill[i][j]=caract;
So the linefeed and carriage return characters would be skipped.
I think you're not taking the carriage-return / linefeed characters into account when reading the input. I would probably use a different technique, where you read a line at a time rather than a single character.
Try testing the character to see if it is a cr/lf and skip it if so.
I can't understand why my program not functioning. It compiles but nothing is printed. I have a 5 character word in file. I need to read line from that file and then split it into char array, which I then want print out.Thanks!
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
public class test {
public static void main(String[] args)
{
BufferedReader line = null;
char[] array = new char[7];
try{
line = new BufferedReader(new FileReader(args[0]));
String currentLine;
while((currentLine = line.readLine()) != null)
{
array = currentLine.toCharArray();
}
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}//try
catch(IOException exception)
{
System.err.println(exception);
}//catch
finally
{
try
{
if(line != null)
line.close();
}//try
catch(IOException exception)
{
System.err.println("error!" + exception);
}//catch
}//finally
} // main
} // test
Your while loop skips every line except the last one so it could be possible that your last line is empty. To display every line you could have:
while ((currentLine = line.readLine()) != null) {
array = currentLine.toCharArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
Or if you just have the 1 line, You could simply use:
String currentLine = line.readLine();
...
Your program prints only last line
You have to Print in loop.
while (....!=null)
{
array = currentLine.toCharArray();
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
}
}
If above was not a problem than check your file permission.
Check your system may be program is not able to read from file due to permission on file.