How to print and remove integers from a file on computer - java

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

Related

Why is there no output when I run my code?

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).

What does this error mean in my project?

Hello I am working on a project and I continue to get an error message and I can't figure out why. Can someone please help?
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.StringIndexOutOfBoundsException;
public class Authorship{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
System.out.println("Name of input file:");
String correctAnswers = scanner.next();
File file =new File(scanner.next());
if(!file.exists()){
System.out.println(" This file does not exist");
} else {
BufferedReader reader = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
int count[] = new int[13];
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for(int i=0;i<line.length;i++){
int wordCount = line[i].length();
count[wordCount-1]++;
totalWordCount++;
}
}
for(int i = 0;i < 13;i++){
float percentage =count[i]*100/totalWordCount;
if(i != 12) {
System.out.printf("Proportion of "+(i+1)+"-letter words: %.2f%%(%d words)", percentage, count[i]);
} else {
System.out.printf("Proportion of 13- (or more)letter words: %.2f%%(%d words)", percentage, count[i]);
System.out.println("\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
}
}
I receive the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Authorship.main(Authorship.java:36)
if wordCount is 0 then [wordCount - 1] is -1
so you are getting ArrayIndexOutOfBoundsException: -1 exception when access -1 index . count[wordCount - 1]//error occured
to avoid this check wordcount length first.access wordCount - 1 only when wordCount > 0
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for (int i = 0; i < line.length; i++) {
int wordCount = line[i].length();
if (wordCount > 0) {
count[wordCount - 1]++;
totalWordCount++;
}
}
}
I believe I fixed your code. It should run fine now.
You needed to change totalWordCount++; to wordCount and *100/totalWordCount; to i
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.StringIndexOutOfBoundsException;
public class Authorship{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
System.out.println("Name of input file:");
String correctAnswers = scanner.next();
File file =new File(scanner.next());
if(!file.exists()){
System.out.println(" This file does not exist");
} else {
BufferedReader reader = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
int count[] = new int[13];
while ((text = reader.readLine()) != null) {
String[] line = text.split(" ");
for(int i=0;i<line.length;i++){
int wordCount = line[i].length();
count[wordCount-1]++;
wordCount++;
}
}
for(int i = 0;i < 13;i++){
float percentage =count[i]*100/i;
if(i != 12) {
System.out.printf("Proportion of "+(i+1)+"-letter words: %.2f%%(%d words)", percentage, count[i]);
} else {
System.out.printf("Proportion of 13- (or more)letter words: %.2f%%(%d words)", percentage, count[i]);
System.out.println("\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
}
}
}

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

JAVA: How to sort strings read from file and output to console in alphabetical order?

I'm looking to sort the contacts read from a file in alphabetical order by last name to the console? How would I go about doing so? The contacts are already written to file starting with the last name, I just want to read them back into the application in alphabetical order when a user wants to view the contacts in the console.
// Read from file, print to console. by XXXXX
// ----------------------------------------------------------
int counter = 0;
String line = null;
// Location of file to read
File file = new File("contactlist.csv");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
counter++;
}
scanner.close();
} catch (FileNotFoundException e) {
}
System.out.println("\n" + counter + " contacts in records.");
}
break;
// ----------------------------------------------------------
// End read file to console. by XXXX
Before printing, add each line to a sorted set, as a TreeSet:
Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lines.add(line);
counter++;
}
for (String fileLine : lines) {
System.out.println(fileLine);
}
package main.java.com.example;
import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
public class ReadFromCSV {
public static void main(String[] args) {
try {
final ClassLoader loader = ReadFromCSV.class.getClassLoader();
URL url = loader.getResource("csv/contacts.csv");
if (null != url) {
File f = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(f));
Set<String> set = new TreeSet<String>();
String str;
while ((str = br.readLine()) != null) {
set.add(str);
}
for (String key : set) {
System.out.println(key);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read names from the file, put them in an object of class SortedSet.

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