Why is there no output when I run my code? - java

I am trying to read a file called ecoli.txt, which contains the DNA sequence for ecoli, and store its contents into a string. I tried to print the string to test my code. However, when I run the program, there is no output. I am still new to java so I am sure there is an error in my code, I just need help finding it.
package codons;
import java.io.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader codons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_string = new StringBuilder();
String line = ecoli.readLine();
while(line != null);
{
dna_string.append(line);
line = ecoli.readLine();
}
String string = new String(dna_string);
System.out.println(string);
ecoli.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
edit:
I was still having trouble getting the program to work the way I wanted it to so I attempted to complete writing the rest of what I wanted in the program and I am still not getting any output. Anyway, this is where I am at now:
package codons;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader filecodons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_sb = new StringBuilder();
String line = ecoli.readLine();
while(line != null)
{
dna_sb.append(line);
line = ecoli.readLine();
}
String dna_string = new String(dna_sb);
ecoli.close();
BufferedReader codons = new BufferedReader(filecodons);
StringBuilder codon_sb = new StringBuilder();
String codon = codons.readLine();
while(codon != null)
{
codon_sb.append(codon);
line = codons.readLine();
}
String codon_string = new String(codon_sb);
codons.close();
for(int x = 0; x <= codon_sb.length(); x++)
{
int count = 0;
String codon_ss = new String(codon_string.substring(x, x+3));
for(int i = 0; i <= dna_sb.length(); i++)
{
String dna_ss = new String(dna_string.substring(i, i+3));
int result = codon_ss.compareTo(dna_ss);
if(result == 0)
{
count += 1;
}
}
System.out.print("The codon '");
System.out.print(codon_ss);
System.out.print("'is in the dna sequence");
System.out.print(count);
System.out.println("times.");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Remove the ; after while(line != null), it causes an infinite loop instead of executing the next instructions.
The reason is explained here: Effect of semicolon after 'for' loop (the question is about the C language, but it is equivalent in Java).

Related

Read, and then split a text file into different arrays

So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}

How to print and remove integers from a file on computer

I am trying to read a file from my computer, and have the system print out the file only containing the letters, and not printing the numbers. I have other functions in my code already so please look near the bottom where I am stuck with arraylist. How do I ignore the integers when printing?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
Scanner myScanner = new Scanner (System.in);
String enteredString = "";
System.out.println("Please enter the characters to search for: ");
enteredString = myScanner.nextLine();
for(int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains(enteredString)) {
System.out.println(myFileLines.get(i));
}
}
ArrayList<String> input = myFileLines;
String extract = input.replaceAll("[^a-zA-Z]+", "");
System.out.println(extract);
}
}
The error is you are applying replaceAll on a list and also the regex is not correct. Something like below will do the job. I am not clear if that's what you want though.
ArrayList<String> input = myFileLines;
for (String e : input) {
String extract = e.replaceAll("\\d+", "");
System.out.println(extract);
}

I am trying to count characters from a within file

What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}

Parsing Data from CSV to Array in Java

I'm trying to import a CSV file into an array that I can use within a Java program. The CSV file has successfully imported itself and the output appears on Terminal but it throws the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at CompareCSV.main(CompareCSV.java:19)
at the end. In addition, when I try to call up elements in the array, it also shows the same error. My code is below:
import java.io.*;
import java.util.*;
public class CompareCSV {
public static void main(String[] args) {
String fileName = "sampledata1.csv";
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are much better off using a proper CSV parser than hacking a faulty one up yourself: http://opencsv.sourceforge.net/
CSV is not the simple format one might be let to think (yes, a line can contain a , that does not separate two pieces of data).
This is the answer for above Question
public class Readline {
/**
* #param args
*/
public static void main(String[] args) {
String fileName = "C:/Users/karthikrao/Desktop/cvsFile.csv";
ArrayList<Integer> margins = new ArrayList<Integer>();
BufferedReader br;
String line, token;
int i;
try {
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
if (margins.size() <= i) {
margins.add((Integer) token.length());
} else {
margins.set(
i,
Math.max(margins.get(i),
(Integer) token.length()));
}
i++;
}
}
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ",\"");
i = 0;
while (st.hasMoreTokens()) {
token = st.nextToken();
System.out.print(token);
for (int j = 0; j < margins.get(i) - token.length(); j++) {
System.out.print(" ");
}
System.out.print("|");
i++;
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I suggest you not re-inventing wheel when there are so many great libraries out there. Try the uniVocity-parsers with the following code snippt as reference:
public static void main(String[] args) throws FileNotFoundException {
/**
* ---------------------------------------
* Read CSV rows into 2-dimensional array
* ---------------------------------------
*/
// 1st, creates a CSV parser with the configs
CsvParser parser = new CsvParser(new CsvParserSettings());
// 2nd, parses all rows from the CSV file into a 2-dimensional array
List<String[]> resolvedData = parser.parseAll(new FileReader("/examples/example.csv"));
// 3rd, process the 2-dimensional array with business logic
// ......
}
As you can see, only 2 lines required to finish the task of parsing csv data into array. Additionally, the library provides full list of features in parsing CSV data with excellent performance.
Looks like your assumption, that a line in the file always has three columns isn't true for all lines. Replace the for loop statement with the following line to eliminate the exception and see, why it happend:
for (int x=0; x<result.length; x++)

How to remove commas from a text file?

I got this far, but it seems that buffer won't take arrays, because first I had it this way
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
// System.out.println (strLine);
String Record = strLine;
String delims = "[,]";
String[] LineItem = Record.split(delims);
//for (int i = 0; i < LineItem.length; i++)
for (int i = 0; i == 7; i++)
{
System.out.print(LineItem[i]);
}
now I leave at this, because it's reading but not taking out commas.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class mainPro1test {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\2010_Transactions.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
String Record = text;
String delims = "[,]";
String[] LineItem = Record.split(delims);
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
of how it should look like
input
Sell,400,IWM ,7/6/2010,62.481125,24988.02,4.43
Sell,400,IWM ,7/6/2010,62.51,24999.57,4.43
output
Sell 400 IWM 7/6/2010 62.481125 24988.02 4.43
Sell 400 IWM 7/6/2010 62.51 24999.57 4.43
If you only want to remove commas from a String, you can use String.replaceAll(",","");
If you want to replace them by spaces, use String.replaceAll(","," "):
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
Easier is to define a new InputStream that just removes the commas...
class CommaRemovingStream extends InputStream {
private final InputStream underlyingStream;
// Constructor
#Override public int read() throws IOException {
int next;
while (true) {
next = underlyingStream.read();
if (next != ',') {
return next;
}
}
}
}
Now you can read the file without commas:
InputStream noCommasStream = new CommaRemovingStream(new FileInputStream(file));

Categories