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();
}
}
Related
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 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 should one change in the code so that instead of entering a string in console, one enters a text name (exmple.txt) to get to the text (where the frequences will be counted)?
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the Text: ");
String s = br.readLine();
System.out.println ("Enter suffix: ");
String sub = br.readLine();
int ind,count = 0;
for(int i = 0; i + sub.length() <= s.length(); i++)
{
ind = s.indexOf(sub, i);
if (ind >= 0)
{
count++;
i = ind;
ind = -1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
First of I will refactor your code like this in order to reuse the calculateOcurrences method. Then I would read the text file line by line and sum all the occurrences by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the file path: ");
final String filePath = br.readLine();
System.out.println ("Enter suffix: ");
final String suffix = br.readLine();
int count = 0;
Path path = FileSystems.getDefault().getPath(filePath);
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
count = count + calculateOcurrences(line,suffix);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
System.out.println("Occurence of '"+suffix+"' in String is "+count);
}
public static int calculateOcurrences(final String text, final String suffix) {
int ocurrences = 0;
for(int i = 0; i + suffix.length() <= text.length(); i++)
{
int indexOfOcurrence = text.indexOf(suffix, i);
if (indexOfOcurrence >= 0)
{
ocurrences++;
i = indexOfOcurrence;
}
}
return ocurrences;
}
}
I am trying to get the number of lines of code from a java file. But I am having trouble counting them.
First I tried to skip them with ifs, but my idea does not work. Now I am counting the same lines with comments, my Java file has this header. Any ideas, I am stuck in how to count them.
My if is for getting the number of lines with the comments block. I trying to make a subtract.
/*
example
example
*/
int totalLoc = 0;
int difference = 0;
while((line =buff.readLine()) !=null){
if((line.trim().length() !=0 &&(!line.contains("/*") ||!line.contains("*/")) )){
if(line.startsWith("/*")){
difference++;
}else if(linea.startsWith("*/")){
difference++;
}else{
difference++;
}
}
}
If you want to count lines in any file write below method and pass the fileName as input to below method and it will return counts.
public int count(String filename) throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try
{
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1)
{
empty = false;
for (int i = 0; i < readChars; ++i)
{
if (c[i] == '\n')
++count;
}
}
return (count == 0 && !empty) ? 1 : count;
}
finally
{
is.close();
}
}
Got the solution try below code it will print all multiline comments as well as total lines of multiline comments found in a file.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LinesOfCode {
public static void main(String[] args) {
try {
String s = readFile("D:\\src\\SampleClass.java");
Pattern p = Pattern.compile("/\\*[\\s\\S]*?\\*/");
Matcher m = p.matcher(s);
int total = 0;
while (m.find()) {
String lines[] = m.group(0).split("\n");
for (String string : lines) {
System.out.println(string);
total++;
}
}
System.out.println("Total line for comments = " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
}
}
http://ostermiller.org/findcomment.html
check out this link it will help you more.
and by using this expression => (/*([^]|[\r\n]|(*+([^/]|[\r\n])))*+/)|(//.)
you can count both comments single line and multi line !!
I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.
You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))
you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");
Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}