Counting number of comments in java - java

I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file
Yes
//comment
yes
yes
/*
if
random
test
test
*/
While the answer should be two comments!
In the following file, it's showing me that I have five comments while I still actually have two
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/

The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:
\u002F* this is a valid comment */
Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.

I think you have a problem in that comments can occur inside or at the end of a line as well...
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.contains("//")) {
count++;
} else if (line.contains("/*")) {
count++;
while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?

I haven't tested your code however, I believe this should work :
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while ((line = br.readLine())!=null && !line.endsWith("'*\'"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
When you meet the /* you should increment the counter and skip the comment section.

Guys here is a easy solution. Just download the cloc software from this link for windows.
This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command
cloc-(version no).exe (folder name)
cloc-1.64.exe main
and have the no of lines, blank line and total no of lines in the code.
For more detail see this: http://cloc.sourceforge.net/

enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {
String line = "";
int comment_count = 0;
int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
line_count++;
if (line.startsWith("//")) {
comment_count++;
single_comment_count++;
} else if (line.startsWith("/*")) {
comment_count++;
multiple_comment_count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
comment_count++;
multiple_comment_count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("comment_count=" + comment_count);
}
}

package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CommentsReading {
public static void main(String[] args) {
String line = "";
int number_of_blocks = 0;
int comment_count = 0;
int line_count = 0;
int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line_count++;
;
if (line.contains("//")) {
if (line.contains("TODO")){
TODO++;
}
comment_count++;
single_comment_count++;
} else if (line.contains("/*") )
{
if (line.contains("TODO")){
TODO++;
}
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
break;
}
while (!(line = br.readLine()).endsWith("'*/'") )
{
line_count++;
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
number_of_blocks++;
break;
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total # of Lines = " + line_count);
System.out.println("Total # of Comment Lines= " +comment_count);
System.out.println("Total # of Single line Comments= " +single_comment_count );
System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );
System.out.println("Total # of Block line Comments = " +number_of_blocks);
System.out.println("No of TODO's = " +TODO);
}
}

Related

How to use BufferedReader in a try catch?

I've been trying to use bufferedreader several times but every time I get some form error. This is time it is "not a statement" and "; expected" also "catch without try". I keep getting errors at the line with the try(bufferedreader) line. Am I using this correct? I am just trying it out and not quite sure how it works. from the online resource I've been looking at my code looks fine. But when I run my own it gives me errors.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Problem2 {
public static void main(String [] args) {
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(New FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}
}
}
1) The errors are simple, firstly you're supposed to use new FileReader (with lowercase n) rather than New FileReader (with uppercase N).
2) you're closing the else block before attaching the catch handlers to the try block.
I have now corrected both issues and the code below should compile.
if(args.length != 1){
System.out.println("Please enter a txt file");
}
else{
String s;
try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
while ( (s = br.readLine()) != null) {
String[] words = s.split("[^a-zA-Z0-9]+");
for(int i = 0; i < words.length; i++){
//code
}
}
br.close();
}catch (FileNotFoundException ex){
System.out.println(ex);
}
catch (IOException ex){
System.out.println(ex);
}
}

reading crossword puzzle txt file

I am new at JAVA and i got no idea how to start this. I was looking for a good start. I need to read a txt file that has a certain format and put it into a view. i first need to read the dimensions of the grid, then the words in the order of the puzzle, then the amount of words needed to be found and last the actual word. If anyone can get me into the right direction with an example, that would really help.
this is the format of the txt file
5 5
abcd
dfad
adfe
lkjl
ekkf
5
realword
realword
realword
realword
realword
EDIT: so this is what i tried after testing to read out the file which works (thanks!). but i get stuk here, i still need to change from char[][] to box[][], since i will be needing it to fill the letterGrid.
import java.io.*;
import java.util.List;
public class Puzzle {
//Box[][] letterGrid;
char[][] letterGrid;
List<Word> wordList;
List<Box> wordInWording;
public Puzzle() {
try {
BufferedReader br = new BufferedReader(new FileReader("..\\word.txt"));
String[] dimensions = br.readLine().split(" ");
letterGrid = new char[Integer.parseInt(dimensions[0])][Integer.parseInt(dimensions[1])];
for (int i = 0; i < letterGrid[0].length; i++) {
String val = br.readLine();
letterGrid[i]= val.toCharArray();
}
//while something something
int r = br.read();
int c = br.read();
letterGrid = new char[r][c];
for (int i = 0; i<r; i++){
String getChar = new String(br.readLine());
for(int j=0; j<c; j++){
letterGrid[i][j] = getChar.charAt(j);
}
}
// String sCurrentLine;
// while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is a good Start:
I will just give you hint on how to read lines from a text file. YOu have to build the logic on your own after reading from it.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You are not supposed to post such questions in SO without even giving it a try. Try to code, if you get stuck post it then and ask for help. Community does not encourage such questions.

Java NumberFormatException Skip Line

I'm writing a program that reads in a list of numbers. Such as:
45
63
74g
34.7
75
I simply want my program to skip lines that contain any letters in them. Any help would be greatly appreciated. Thanks!
If it makes a difference, here is my code:
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
catch (NumberFormatException err) {
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
When an exception is thrown, execution jumps to the catch block. In what you have, this is after the loop, so the loop doesn't continue, just add a try around parseInt.
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
try{
int num = Integer.parseInt(nums[i]);
if (num != -1) {
sum += num;
}
} catch( NumberFormatException nfe )
{
// maybe log it?
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
// catch (NumberFormatException err) {}
finally {
try {
if (reader != null){
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
Also note, you are using Integer.parseInt which will throw an exception with the input "34.7", so maybe you wish to use Double.parseDouble
How about using a regex? Like for example:
if (currentLine.matches(".*[a-zA-Z].*")) {
//letters contained.
} else {
//no letters contained.
}
see regex demo: http://regex101.com/r/rQ6oR1
you can try this :
import java.io.*;
public class ScoreReader {
public static void main(String[] args) {
BufferedReader reader = null;
try {
String currentLine;
reader = new BufferedReader(new FileReader("QuizScores.txt"));
while ((currentLine = reader.readLine()) != null) {
int sum = 0;
String[] nums = currentLine.split("\\s+");
for (int i = 0; i < nums.length; i++) {
if (isInt(num)) {
sum += num;
}
}
System.out.println(sum / nums.length);
}
} catch (IOException err) {
err.printStackTrace();
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException err) {
err.printStackTrace();
}
}
}
public boolean isInt(String num)
{
boolean flag=false;
try
{
int i=Integer.parseInt(num);
flag=true;
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return flag;
}
}
Based on your comment. if your file contain one number per line . then this would be easiest way.
Scanner sc = new Scanner(new File("QuizScores.txt"));
int sum = 0;
int count =0;
while( sc.hasNext()){
String tmpNum = sc.next();
if (isNumeric(tmpNum)){
sum = sum + (int) Double.parseDouble(tmpNum); // if you want t capture in double use Double instead.
count++;
}
}
System.out.println(sum/count);
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

How to detect first and last line during reader.readLine()?

I am reading each line of the file in the below way
BufferedReader in = new BufferedReader(new FileReader(inFile));
while (null != (line = in.readLine())) {
}
I want to do some validation in the first line and last line alone. Is there any
way to check if it's a first line and last line inside the while loop
while (null != (line = in.readLine())) {
if(firstlineoffile) {
}
else if (lastlineoffile) {
}
else
{
}
}
Cool question. I played a bit round it and here's an SSCCE, just copy'n'paste'n'run it.
package com.stackoverflow.q2292917;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Test {
public static void main(String... args) throws IOException {
// Create test file.
File file = new File("/test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("line 1");
writer.println("line 2");
writer.println("line 3");
writer.println("line 4");
writer.println("line 5");
writer.close();
// Read test file.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
System.out.println("first line: " + line);
} else if (last) {
System.out.println("last line: " + line);
} else {
System.out.println("normal line: " + line);
}
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
// Delete test file.
file.delete();
}
}
Output:
first line: line 1
normal line: line 2
normal line: line 3
normal line: line 4
last line: line 5
I however question the readability and interpretability by starters... ;)
String currentLine = in.readLine();
String nextLine = in.readLine();
boolean hasStarted = false;
while(null != currentLine){
if(!hasStarted){
//first line.
hasStarted = true;
}
//all your processing here.
if(null == nextLine){
//last line, cause there's nothing else coming up
}
currentLine = nextLine;
nextLine = in.readLine();
}
if you add a count, and rearrange your code a little, this should work (I haven't tested this so there may be syntax errros):
int count = 0;
String line = in.readLine();
while (line!=null) {
String currLine = line;
if(count==0){
//currLine is the first line
}
line = in.readLine();
if(line==null){
//currLine is the last line
}
if(count>0 && line!=null){
//do something with lines in between
System.out.println(currLine);
}
count++;
}
public class Vomitfirstline {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("Path"));
br.readLine();
{
while ((sCurrentLine = br.readLine()) != null)
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Someone might well come up with a more elegant solution than this, but here we go:
boolean isFirstLine = true;
do{
String line = in.readLine();
if(isFirstLine){
//this is the first line
isFirstLine = false;
}
else if(line==null){ //previous line was the last line
in.reset();
line = in.readLine();
//do last line specific stuff
break;
}
else {
//do stuff for lines in between
}
in.mark(100);
}while (line!=null);
I haven't tested this, so there might be minor errors. I haven't sorted out exception handling in this code. readLine(), mark() and reset() throw IOException and mark() can also throw IllegalArgumentException

Categories

Resources