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);
}
}
Related
I have a simple Java IO program which reads from a text file of numbers that looks like this :
1
2
3
4
5
6
7
8
9
17
It's supposed to simply print the lines in this text file to the console, and then tell me what the last line was. But it's printing the last line, here 17, as just 7 -
Here's my code so far :
import java.lang.*;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ParentClass3{
static int lastLine = 0;
public static void main(String[] args) {
File file = new File("C:\\Java_Scratch_\\someFile.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
try {
int i = sc.nextInt();
System.out.println(i);
} catch (Exception e) {
System.out.println (" here is the stack trace " + e.getStackTrace() );
System.out.println (" here is the stack trace " );
}
}
sc.close();
} // END big-outer-Try
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
int i = ParentClass3.countLines("C:\\Java_Scratch_\\someFile.txt");
System.out.println("There are " + i + " lines");
}
catch (IOException ioe) {
System.out.print("ioe" + ioe.getStackTrace() );
}
}
// putting the count function
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
int lastline = 0;
boolean empty = true;
while ( (readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i){
Byte b = c[i];
int xx = b.intValue();
lastLine = xx;
if (c[i] == '\n'){
++count;
empty = true;
} else {
empty = false;
}
}
}
if (!empty) {
count++;
}
int asciiVal = lastLine;
int lastLine2 = Character.getNumericValue(asciiVal);
System.out.println("the last line was " + lastLine2);
return count;
} finally {
is.close();
}
}//END method countLines
// end-count_func
}
How would I fix it, so that it says "the last line was 17" , rather just just 7 ?
the methos nextLine() should work, although I don't remember if that input would be parsed to a String, I guess that wouldn't affect, but anyway...
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
String line;
try {
while( (line = in.readLine()) != null ) {
System.out.println(line);
lineCount++;
charCount += line.length();
String[] words = line.split("\\W");
wordCount += words.length;
}
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
} catch (IOException e) {
e.printStackTrace();
}
}
Straight to the point: How do I exit the above while-loop? I've read on another question that readLine() returns null when there is no more line left to read, but how do I do that using Eclipse's console?
The only way I can manage to break the loop is to add in cases, such as
if(line.length() == 2 || line.equals("exit")))
break;
if you just want to read a line, why do you need while loop?
or if you want multiple inputs to be taken then you should specify how many inputs are to be taken in first readline();
otherwise i hope below code will resolve your issue :)
public class TestRandomArray {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
try {
String line = in.readLine();
lineCount++;
charCount += line.length();
String[] words = line.split(" ");
wordCount += words.length;
System.out.println("charCount = " + charCount);
System.out.println("wordCount = " + wordCount);
System.out.println("lineCount = " + lineCount);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my logic for word frequency. I'm not supposed to use HashMap to store the frequency of a word. I am getting an ArrayIndexoutofBoundsException, but can't figure out why.
Program:
package thirdassignments;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordFreq2 {
public void Working() {
try {
File file = new File("C:/Users/kishansr/Desktop/file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String sentence = stringBuffer.toString();
String [] words = sentence.split("\\s+"); // splits by whitespace
for (String word : words) {
System.out.println(word);
}
String word1[] = new String [100000];
int count[] = {0}, count1 = 0;
for (String word : words) {
count1 = count1 + 1;
}
System.out.println("COunt :" + count1);
for (String word : words) {
for (int i = 0 ; i < count1 ; i++) {
if (word1[i] != word) {
word1[i] = word;
count[i] = 1; // here the exception is oocuring
}
else if (word1[i] == word) {
count[i] = count[i] + 1;
}
}
}
for (int i = 0 ; i < count1 ; i++) {
System.out.println(count[i] + " : " + word1[i]);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String [] args) {
// TODO Auto-generated method stub
WordFreq2 wf = new WordFreq2();
long startruntime = System.nanoTime();
wf.Working();
long endruntime = System.nanoTime();
System.out.println( "start time: " + startruntime + " end time :" + endruntime + " diferrence: " + (endruntime - startruntime));
}
}
Output :
This
is
the
Hewlett
Packard
company
.
This
Company
is
spread
over
the
world
and
has
established
its
footprints
in
almost
all
countries
.
It
has
a
huge
employee
count
and
has
more
women
employees
than
male
employees
.
COunt :39
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
You've instantiated the count[] array with a size of 1. It needs to be at least as large as your array.
Try change this line
String word1[]=new String[100000];
int count[]={0},count1=0;
for (String word : words) {
count1=count1+1;
}
to
String word1[]=new String[100000];
int count1=0;
for (String word : words) {
count1=count1+1;
}
count[]= new int[count1];
Your count array :
int count[]={0};
has a single element
So you'll get an exception for count[i] for any i>0.
Perhaps you should initialize it to the same length as the word1 array :
int count[]= new int[100000];
In addition, replace word1[i]==word with word1[i].equals(word).
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!
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
}
}