reading line and splitting to char array - java

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.

Related

Extra charcters in .csv output

After importing a CSV file and sorting it in to a 2-Dimensional array I get a couple of weird characters in only the first and possibly the last cell.
Expected output: S1358_R1
Actual output: S1358_R1
Does anyone know why these extra characters show up? The code used to do this is included below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class open2 {
public static void main(String[] args) {
String line = "";
String splitBy = ",";
try {
//parsing a CSV file into BufferedReader class constructor
int i = 0;
String[][] ss = new String[10000][10000];
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\micha\\Documents\\spreadsheet.csv"));
while ((line = br.readLine()) != null) //returns a Boolean value
{
String[] cells = line.split(splitBy);
for (int j = 0; j < cells.length; j++) {
ss[i][j] = cells[j];
} // use comma as separator
i = i + 1;
}
System.out.println(ss[0][0]);
} catch (IOException e) {
e.printStackTrace();
}
}
}

JAVA - reading from text file, recognizing new lines

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);
}
}

How to print multiple lines from text files in Java?

I have a text file that contains three lines of code.
That is,
Hello.
How may I help you?
What can I do for you today?
I tried printing the first line and it worked.Now I want to print the rest of the lines in the console but it's only displaying first line 4 times like this.
Hello.
Hello.
Hello.
Hello.
Below is the code that I am trying to run and the file is in root folder.
public class Test
{
public static void main(String[] args)
{
int counter = 0;
/*open the file */
BufferedReader reader = null;
String greeting = null;
int rand;
File file = new File("Greetings.txt");
try
{
reader = new BufferedReader(new FileReader(file));
/*read the file*/
String greetingPicker = null;
/*single greeting*/
/*greeting = greetingPicker;*/
List<String> listOfGreetings = new ArrayList<String>();
while ((greetingPicker = reader.readLine()) != null)
{
listOfGreetings.add(greetingPicker);
}
reader.close();
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
greeting = listOfGreetings.get(rand - 1);
for (int i = 0; i < listOfGreetings.size(); i++)
{
System.out.println(listOfGreetings.get(counter));
}
} catch (Exception e)
{
System.out.println("File cannot be found!!");
}
}
}
You are getting the value for the wrong index: You mistakenly used counter instead of i in your loop. Change this
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(counter));
}
to this:
for(int i=0; i < listOfGreetings.size(); i++){
System.out.println(listOfGreetings.get(i));
}
By the way, you are using Math.random() and it is instantly converted to a int, because you forgot to add correct parentheses, so change this
rand = (int) Math.random() * (listOfGreetings.size()) + 1;
to this:
rand = (int) (Math.random() * (listOfGreetings.size()) + 1);
You dont need your counter, use i ! ;)
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Just change
System.out.println(listOfGreetings.get(counter));
by
System.out.println(listOfGreetings.get(i));
You forgot to change the counter.
You don't need to use counter, and put close in the end like this:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
reader.close();
The "counter" variable here is not being incremented:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(counter));
}
You should change it to "i" instead:
for(int i=0; i < listOfGreetings.size();i++){
System.out.println(listOfGreetings.get(i));
}
Try using the chunk below. It's simpler and works perfectly.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileReader{
public static void main(String[] args){
//define file path
String stringFileToRead = "Greetings.txt";
//the file
File stringFile = new File(stringFileToRead);
//Scanner object to take input from the file
Scanner fileToRead = null;
try{
//Read the file
fileToRead = new Scanner(stringFile);
}
//catch exception
catch (Exception e){
System.out.println("Unable to open file.");
System.exit(0);
}
//print the content of the file
System.out.println("The file contains the following contents:\n");
int lineNum = 1;
while(fileToRead.hasNextLine()){
String line = fileToRead.nextLine();
System.out.println("Line "+lineNum+": "+line);
lineNum++;
}
}
}

java.util.NoSuchElementException Not printing desired output

I'm writing a Java program to try to parse a text file and store the contents of it in a matrix. The following is my Java code:
import java.io.*;
import java.util.*;
public class Viterbi
{
String[][] gmatrix = new String[50][4];
float[] pmatrix = new float[50];
public Viterbi(String filename)
{
BufferedReader br = null;
try
{
String currentline;
StringTokenizer st;
br = new BufferedReader(new FileReader(filename));
while((currentline = br.readLine()) != null)
{
st = new StringTokenizer(currentline, ";");
while(st.hasMoreTokens())
{
for(int i=0; i<50; i++)
{
for(int j=0; j<4; j++)
{
gmatrix[i][j] = st.nextToken();
System.out.println("i --> " + i + " j--> " + j + ": " + gmatrix[i][j]+"\t");
}
}
}
}
for(int i=0; i<50; i++)
{
for(int j=0; j<3; j++)
System.out.print(gmatrix[i][j]+"\t");
System.out.println("");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
Viterbi v = new Viterbi("rules.txt");
}
}
And here's the contents of the text file:
S;a;S;0.6
S;b;X;0.4
X;c;$;0.1
X;X;$;0.9
I want the output to be displayed in the gmatrix as:
S a s
S b X
X c $
X X $
But for some reason I get the following output and exception:
i --> 0 j--> 0: S
i --> 0 j--> 1: a
i --> 0 j--> 2: S
i --> 0 j--> 3: 0.6
java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Viterbi.<init>(Viterbi.java:27)
at Viterbi.main(Viterbi.java:62)
How can I print the correct output as desired?
In your code, you are only calling hasNextToken() once at the start of the while condition. You need to call hasNextToken() as many times as nextToken(), to make sure that nextToken() will work. The reason you don't have any more tokens on the line is that there are only 4 tokens per line (apparently) but you have two for loops that will try to call nextToken() a total of 50*4=200 times.
Alternatively to how you are doing this: you could just split the currentLine on ";" with the split() method and then loop through the returned String[] elements.
In your first while loop, you are actually trying to populate the whole gmatrix by parsing a single line of the input file. This is not what you expect. Since there are only 4 tokens in the first line, you get the exception when you are trying to call st.nextToken() to get the next (non-existing) token when the program is trying to get gmatrix[1][0].
To correct your code, you should check and read a new input line in your first for(int i = ...) loop, and remove the 2 out-most while loops.
Example:
for(int i = 0; ...){
// check if there is another line in input;
// tokenize a line of input;
for(int j = 0; ...){
// get a token and populate one element in gmatrix;
}
}
Instead of using the two while loops.

How to find smallest value(from values given in a txt file) using BufferedReader in java

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
}
}

Categories

Resources