I want to calculate the number of lines of code within a program, and for which I had already written code which counts the number of ;. It works fine, but not in some situations like where there is no ; present (like if and while statements). In this case I had stored some of the keywords in an array of strings and I want to search for that keyword by using readLine(). If it works fine then I will increment it by 1, but it's not working. I had tried a lot but it is not working at all, and it is showing the Exception. As Demo.java you can use your own code.
Classdetect1.java
import java.io.*;
public class Classdetect1
{
public static void main(String[] args) throws IOException
{
int i=0,j=0,k=0,p;
String str1[]={"if","else","else if","while","for","goto","do"};
// Open the file
FileInputStream fstream = new FileInputStream("Demo.java");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
if (in == null){
System.out.println("File is blank");
System.exit(0);
}
while (i != -1)
{
i = in.read();
if(i==';' || i=='{')
{
j=j+1;
}
if(i=='\'')
{
while(in.read()!='\'')
continue;
}
if(i=='\"')
{
while(in.read()!='\"')
continue;
}
if(i=='(')
{
while(in.read()!=')')
continue;
}
while ((strLine = br.readLine()) != null)
{
for(p=0;p<7;p++)
{
if(str[p].equals(strLine))
{
k=k+1;
}
}
}
System.out.println("Line of =" + k);
}
System.out.println("Total Line of code=" + j);
}
}
In Java all statements end either with ; or with a block within { }. Some examples:
System.out.println("One statement");
while (str.equals("One block of statements + one statement"))
{
System.out.println("One statement");
}
Furthermore, the ; does not need to be on the same line at all:
System.out.println(
"One statement"
);
So you could simply count all ; (end of a statement) and all { (end of a statement, start of a block) and it will be fairly accurate.
if (true)
{ // One statement ending with '{'
doSomething(); // One statement ending with ';'
while (false)
{ // One statement ending with '{'
doSomethingElse(); // One statement ending with ';'
}
}
// 4 statements in total.
Of course, there are (as always) some exceptions:
if (true) doSomething(); // One statement, or two?
do { doSomething(); } while (true); // Three statements, or two?
Try this:
BufferedReader br = new BufferedReader(new FileReader(new File("C:/lines.txt")));
String s = "";
String text = "";
//save all the file in a string
while ((s = br.readLine()) != null) {
text += s + "\n";
}
//remove empty lines with a regex
String withoutEmptyLines = text.replaceAll("(?m)^[ \t]*\r?\n", "");
//lines of code = text with newline characters length - text without newline characters length
int linesOfCode = withoutEmptyLines.length() - withoutEmptyLines.replaceAll("\n", "").length();
System.out.println("Lines: "+linesOfCode);
My C:/lines.txt file:
01. a
02.
03. b
04. c
05. c
06. d
07. as
08. d
09. asd
10. asd
11. a
12.
13.
14.
15. asd
16.
17. asd
18.
19.
20.
21. asdasd
22.
23.
24.
With this file, the output is:
Lines: 13
Hope this helps
Related
I have program that has a section that requires me to read and append items to a txt file. I know how to do basic reading and appending but I am confused as to how I would read every 4th line in a txt file and then store it in a variable. Or even every alternate line.
Also, if there are double valued numbers, can I read it as a number and not a string?
To read say every fourth line from a text file you would read a line and update a counter. When the counter reaches 4, you save the line in a String variable. Something like this would do the job:
import java.io.*;
public class SkipLineReader {
public static void main(String[] args) throws IOException {
String line = "";
String savedLine = "";
int counter = 0;
FileInputStream fin = new FileInputStream("text_file.txt");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(fin));
// Save every fourth line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter == 4 ) {
savedLine = line;
System.out.println(line);
}
}
}
}
To save every alternate line, you would save the line every time the counter reaches two and then reset the counter back to zero. Like this:
// Save every alternate line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter % 2 == 0 ) {
counter = 0;
savedLine = line;
System.out.println(line);
}
}
As for reading doubles from a file, you could do it with a BufferedReader and then use Double's parseDouble(string) method to retrieve the double value, but a better method is to use the Scanner object in java.util. The constructor for this class will accept a FileInputStream and there is a nextDouble() method that you can use to read a double value.
Here's some code that illustrates using a Scanner object to grab double values from a String (to read from a file, supply a FileInputStream into the Scanner class's constructor):
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6 true";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
// find the next double token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a double, print found and the double
if (scanner.hasNextDouble()) {
System.out.println("Found :" + scanner.nextDouble());
}
// if a double is not found, print "Not Found" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
}
This is my code example.
public static void main(String[] args) throws Exception {
// Read file by BufferedReader line by line.
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null) {
line = line.trim();
System.out.println(line);
// Using regular expression to check line is valid number
if (!line.trim().equals("") && line.trim().matches("^\\d+||^\\d+(\\.)\\d+$")) {
double value = Double.valueOf(line.trim());
System.out.println(value);
} else {
String value = line.trim();
System.out.println(value);
}
// Read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm trying to count the number of mutations in a MAF file. I originally wrote this code in python and it worked perfectly fine, but when I translated it to Java it stopped working. In the output file the number of mutations is always one. What am I doing wrong here?
package dev.suns.bioinformatics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
public class Main {
static String filePath = "C:/Users/Matthew/Bioinformatics/Data Files/DLBC.maf";
static String fileName = "DLBC_Info.txt";
public static void main(String[] args){
createFile(filePath, fileName);
}
public static void createFile(String filePath, String fileName){
BufferedReader br = null;
String line = "";
String delimiter = "\t";
String geneSymbol = "";
String newGene = "";
int count;
try {
PrintWriter writer = new PrintWriter(fileName);
br = new BufferedReader(new FileReader(filePath));
writer.println("Gene" + "\t" + "Mutations" + "\n");
br.readLine();
while ((line = br.readLine()) != null){
String[] splitFile = line.split(delimiter);
newGene = splitFile[0];
if(geneSymbol == ""){
geneSymbol = newGene;
}
else if(newGene == geneSymbol){
#This is here I am having trouble. I have this if-statement to check if the gene appears more than once in the .maf file, but nothing is ever entering this.
count++;
}
else{
count++;
writer.println(geneSymbol + "\t" + count + "\n");
geneSymbol = newGene;
count=0;
}
}
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is what the first few lines of the file look like
Gene Mutations
A1CF 1
A2M 1
A2M 1
A2ML1 1
A4GALT 1
AADAC 1
AADACL3 1
AAED1 1
AAGAB 1
AAGAB 1
AARD 1
AARS2 1
AARS2 1
AARS2 1
In java you need to compare strings using equals function. This should work-
else if(newGene.equals(geneSymbol)){
#This is here I am having trouble. I have this if-statement to check if the gene appears more than once in the .maf file, but nothing is ever entering this.
count++;
}
"==" checks for the reference. whether they are same string objects. In order to compare values of string you need to use equals() function.
I have a text file, and when I read each line of the file and write it in array. I want to check if the character is not a dollar sign '$' . If it is, then Jump to next character and write the following part till the next dollar sign in next array. Therefore to divide each line in 3 parts, each part in different array.
Appreciate your time and help!
public void retrieveFromTxt() throws IOException
{
textArea.setText(" ");
String fileName = "Name_Of_City.txt";
String line = " ";
String entry = null;
y = 0;
char letter = '$', value = ' ';
FileReader fileReader = new FileReader(fileName);
BufferedReader br1 = new BufferedReader(fileReader);
String TextLine = br.readLine();
x = 1; // Random Variable to jump from character to character in array.
// To Get Values Back from FIle Each value in correct array, I seperated each value with "$" sign
// Checking each letter and printing it to array[y] possition until the $ sign is met, then jump over it and continue in other array.
try {
while(y < 19) {
while(TextLine != null) {
while(TextLine.charAt(x)!=(letter)) {
line = line + TextLine.charAt(x);
Country[y] = ( line );
x++;
}
}
while(TextLine != null) {
while(TextLine.charAt(x)!=(letter)) {
line = line + TextLine.charAt(x);
City[y] = ( line );
x++;
}
}
while((line = br1.readLine()) != null) {
while(line.charAt(x)!=(letter)) {
Population[y] = (textArea.getText()+ entry );
x++;
}
}
y++;
textArea.setText(textArea.getText()+ "\n" );
}
}
catch(FileNotFoundException error) {
//Exception can be met if program cannot find the file , in that case messageDialog will pop up with help message
JOptionPane.showMessageDialog(null,"Missing file"+", " + fileName + ", for a support contact oleninshelvijs#gmail.com!" ) ;
}catch (StringIndexOutOfBoundsException err){}
br1.close();
}
}
Try using the string.split function. You can do:
String s = "my$sign"
String parts[] = s.split("\\$")
Now parts[0] will hold "my" and parts[1] will hold "sign".
Edit: As pointed out by user Ukfub below, you will need to escape the symbol. Updating my code to reflect.
String parts[] = s.split("$")
That will not work because the parameter for the "split" method is a regular expression. You have to escape the special character '$':
String parts[] = s.split("\\$")
I am working on a program that reads 5 different files containing code that is improperly indented. I have to write a method that properly indents the code and prints it to the console and a new file, given a tab size and the names of the input and output files as parameters. My code so far runs through and indents every line and then tries to determine when to indent another tab or unindent.
public static void justifyJava( String inputFileName, String outputFileName,
int tabSize ) throws FileNotFoundException {
String one_tab = "";
for (int i = 0; i < tabSize; i++) {
one_tab += " ";
}
Scanner input = new Scanner( new File (inputFileName));
PrintStream out = new PrintStream ( new File (outputFileName));
int lineCount = 0;
while ( input.hasNextLine() ) {
String line = input.nextLine();
line = one_tab + line.trim();
lineCount++;
if (lineCount == 1){
line = line.substring(tabSize);
}
else if (lineCount == 2){
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next();
if (token.length() <= 2) {
line = line.substring(tabSize);
}
}
}
else if (line.contains("{") && lineCount > 2){
System.out.println(line);
out.println(line);
line = one_tab + input.nextLine();
while(!(line.contains("}"))){
line = one_tab + line;
System.out.println(line);
out.println(line);
line = input.nextLine();
}
line = one_tab + line;
}
else if (line.contains("}") && input.hasNextLine()){
line = one_tab + line;
}
else if (!(input.hasNextLine())) {
line = line.substring(tabSize);
}
System.out.println(line);
out.println(line);
}
}
This way is becoming very tedious because of how many situations i have to account for especially since the code in these files use different curly brace styles. Essentially all I'm trying to do is indent every line that follows an opening curly brace by one tab and unindent every line that follows a closing curly brace by one tab. Is there an easier way to do this?
Determining "how many times" you have to indent a line is the same as knowing how many blocks of code opened before this line. To this end, you detect a new block of code if:
The string contains an opening bracket {.
The string contains a control statement, e.g. if.
The second approach is harder, since you have to determine if the string is actually a control statement and not part of a variable name.
Hence, a simple program, that does not cover every possible coding standard, but will work pretty decently works like this:
Search for an opening bracket that does not belong to a comment.
When you find it, recursively call the method passing the new indentation size.
Return after finding the end of the code block.
Here goes a MWE that works for most simple cases. It is able to detect opening and closing brackets outside strings, and does not search inside comment lines.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaIndent {
public static void main(String[] args) {
try {
JavaIndent.justify("path/to/input.java", "path/to/output.java", 4);
} catch (FileNotFoundException ex) {
System.out.println("File not found...");
}
}
public static void justify(String inputFileName, String outputFileName,
int tabSize) throws FileNotFoundException {
String one_tab = "";
for (int i = 0; i < tabSize; i++) {
one_tab += " ";
}
Scanner input = new Scanner(new File(inputFileName));
PrintStream out = new PrintStream(new File(outputFileName));
JavaIndent.justifyRecursion(one_tab, "", input, out);
}
private static String justifyRecursion(String base_tab, String tab, Scanner input, PrintStream out) {
String line;
boolean flag_open, flag_close, flag_comment, flag_empty;
while (input.hasNextLine()) {
line = input.nextLine().trim();
flag_open = JavaIndent.contains(line, "{");
flag_close = JavaIndent.contains(line, "}");
flag_empty = line.length() == 0;
flag_comment = (flag_empty) ? false : line.charAt(0) == '/';
if (flag_comment || flag_empty) {
out.println(tab + line);
} else if (flag_close) {
return line;
} else if (flag_open) {
out.println(tab + line + "ENTERED OPEN");
line = JavaIndent.justifyRecursion(base_tab, tab + base_tab, input, out);
out.println(tab + line);
// Handles statements like } else { and sequences of these.
flag_open = JavaIndent.contains(line, "{");
while (flag_open) {
line = JavaIndent.justifyRecursion(base_tab, tab + base_tab, input, out);
out.println(tab + line);
flag_open = JavaIndent.contains(line, "{");
}
} else {
// Just a regular line, nothing special
out.println(tab + line);
}
}
return "";
}
private static boolean contains(String line, String sequence) {
String current = "";
char ch, last_ch = ' ';
int count_quotation = 0;
ArrayList<String> code_without_strings = new ArrayList<>();
for (int k = 0; k < line.length(); ++k) {
ch = line.charAt(k);
if (ch == '"' && count_quotation == 0 && last_ch != '\'') {
code_without_strings.add(current);
current = "";
++count_quotation;
} else if (ch == '"' && count_quotation == 1) {
if (last_ch != '\\') {
count_quotation = 0;
}
}
if (count_quotation == 0) {
current += ch;
}
last_ch = ch;
}
code_without_strings.add(current);
for (String code : code_without_strings) {
if (code.contains(sequence))
return true;
}
return false;
}
}
However, one still needs to consider statements such as this:
if (condition)
System.out.println("This should be indented, but it won't be...");
and this:
/**
* This is just a comment, but the program will indent from here on {.
*/
Try using JavaIndent to indent JavaIndent.java and verify that at the very end you will get
if (code.contains(sequence))
return true;
instead of
if (code.contains(sequence))
return true;
i have written the following code to count the number of character excluding white spaces,count number of words,count number of lines.But my code is not showing proper output.
import java.io.*;
class FileCount
{
public static void main(String args[]) throws Exception
{
FileInputStream file=new FileInputStream("sample.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(file));
int i;
int countw=0,countl=0,countc=0;
do
{
i=br.read();
if((char)i==(' '))
countw++;
else if((char)i==('\n'))
countl++;
else
countc++;
}while(i!=-1);
System.out.println("Number of words:"+countw);
System.out.println("Number of lines:"+countl);
System.out.println("Number of characters:"+countc);
}
}
my file sample.txt has
hi my name is john
hey whts up
and my out put is
Number of words:6
Number of lines:2
Number of characters:26
You need to discard other whitespace characters as well including repeats, if any. A split around \\s+ gives you words separated by not only all whitespace characters but also any appearance of those characters in succession.
Having got a list of all words in the line it gets easier to update the count of words and characters using length methods of array and String.
Something like this will give you the result:
String line = null;
String[] words = null;
while ((line = br.readLine()) != null) {
countl++;
words = line.split("\\s+");
countw += words.length;
for (String word : words) {
countc += word.length();
}
}
A new line means also that the words ends.
=> There is not always a ' ' after each word.
do
{
i=br.read();
if((char)i==(' '))
countw++;
else if((char)i==('\n')){
countl++;
countw++; // new line means also end of word
}
else
countc++;
}while(i!=-1);
End of file should also increase the number of words (if no ' ' of '\n' was the last character.
Also handling of more than one space between words is still not handled correctly.
=> You should think about more changes in your approach to handle this.
import java.io.*;
class FileCount {
public static void main(String args[]) throws Exception {
FileInputStream file = new FileInputStream("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(file));
int i;
int countw = 0, countl = 0, countc = 0;
do {
i = br.read();
if ((char) i == (' ')) { // You should also check for other delimiters, such as tabs, etc.
countw++;
}
if ((char) i == ('\n')) { // This is for linux Windows should be different
countw++; // Newlines also delimit words
countl++;
} // Removed else. Newlines and spaces are also characters
if (i != -1) {
countc++; // Don't count EOF as character
}
} while (i != -1);
System.out.println("Number of words " + countw);
System.out.println("Number of lines " + countl); // Print lines instead of words
System.out.println("Number of characters " + countc);
}
}
Ouput:
Number of words 8
Number of lines 2
Number of characters 31
Validation
$ wc sample.txt
2 8 31 sample.txt
Try this:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileCount {
/**
*
* #param filename
* #return three-dimensional int array. Index 0 is number of lines
* index 1 is number of words, index 2 is number of characters
* (excluding newlines)
*/
public static int[] getStats(String filename) throws IOException {
FileInputStream file = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(file));
int[] stats = new int[3];
String line;
while ((line = br.readLine()) != null) {
stats[0]++;
stats[1] += line.split(" ").length;
stats[2] += line.length();
}
return stats;
}
public static void main(String[] args) {
int[] stats = new int[3];
try {
stats = getStats("sample.txt");
} catch (IOException e) {
System.err.println(e.toString());
}
System.out.println("Number of words:" + stats[1]);
System.out.println("Number of lines:" + stats[0]);
System.out.println("Number of characters:" + stats[2]);
}
}