hello.
I need some help on our implementation on lines of code program.

here's the algorithm we have:

1. The LOC program will start by asking for the filename of the program to be counted.
2. Browse for the filename of the program to be used.
3. The contents of the file will be stored to a temporary storage.
4. Declare a count variable and initialize it to zero.
5. Read the code line by line.
6. If there is at least one character in a line, the count variable will be incremented.
7. Display the contents of the count variable as the number of lines of the code.

II would like to ask any ideas, or any insights on what you think of the algo. We will implement this using java.

If you allow entry of filename and then search for the files, you'll have to be ready to handle multiple files with the same name. (ie, programs/java/foo.java and programs/java/bar/foo.java) An easier task would be to ask the user to operate a standard file chooser, where they have to actually specify a path to the file. This is already available in Swing, or you could implement it yourself if you want.

Also, I imagine that it would make sense to just check the return from reading the nextLine() (of whatever input method you favor). If it's not null, increment your pointer and move one, no need to read the file into memory for the application as described. You might have a future expansion of the application in mind, though, or you might want to do it for its own sake, both respectable reasons to do this, but there's no need for what you're describing.

All in all, this looks like a solid plan of attack for the basic project you're describing.

If you want to get fancy, try to report back some facts about the file: number of lines, number of uncommented lines, number of methods. Average number of lines per method. Number of fields declared in this class, their names, and what sort of access they have. That sort of thing. You should be able to do all of these without loading the whole file into memory. They'll all require that you learn a bit of parsing, which is worth doing.

import java.io.*;

class FileRead {
   public static void main(String args[]){
      try{
    // Open the file that is the first
    // command line parameter
    //the text file is in the project
    FileInputStream fstream = new FileInputStream("xanadu.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    int count = 0;
    int count2 = 0;
    //Read File Line By Line
    while((strLine = br.readLine())!= null ){
    	if (strLine.trim().length() != 0){
    		System.out.println(strLine);
    		count++;
    	}else{
    		count2++;
    	}
    }
    System.out.println("number of lines:" + count);
    System.out.println("number of lines:" + count2);
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
}
}

Im having a difficulty applying in here the browse thing.
Also, does the code follow the algorithm besides the file browse?

Your code shown above is correct. I have tested with a known file. The result is correct. AS long as the browsing files is concerned, as jon.kiparsky indicated, it is already available in Swing. For example, the class FileDialog is a candidate for this purpose. Since its constructor requests a parent frame , as written in Java API, the class you define has to inherit JFrame. I have modified your code as follows. You have to modify your main method accordingly. Attached please the code altered for your reference.

import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
	static File name;  // it is created in constructor, then used in main
	static int count =0; // count the number of lines where characters are found
	static int count2=0; // count the nubmer of empty lines
	
public 	FileRead(){  // constructor for FileRead
	try{
      FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD); 
      fd.setDirectory(System.getProperty("user.dir")); // the window starts with current folder
      fd.setVisible(true);	
   	  name= new File(fd.getDirectory(), fd.getFile());
   	 }catch(Exception e){
   	 	System.err.println(e.getMessage());
   	 	}
   	setSize(400,400);
   	setVisible(true);
   	 }

Good luck.

Edited 6 Years Ago by tong1: n/a

Attachments
import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
	static File name;
	static int count =0;
	static int count2=0;
	
public 	FileRead(){
	try{
	  FileDialog fd = new FileDialog(null, "Open a document", FileDialog.LOAD); 
      fd.setDirectory(System.getProperty("user.dir")); 
      fd.setVisible(true);	
   	  name= new File(fd.getDirectory(), fd.getFile());
   	 }catch(Exception e){
   	 	System.err.println(e.getMessage());
   	 	}
   	setSize(400,400);
   	setVisible(true);
   	 }
   	 
   	 public void paint(Graphics g){
   	 	super.paint(g);
   	 	g.drawString("Testing open file", 30,100);
   	 	g.drawString("Number of characters' lines: " + count,30,200);
   	 	g.drawString("Number of empty lines :" + count2, 30, 250);
   	 }
		
   public static void main(String args[]){
   	FileRead fr = new FileRead();
   	fr.setDefaultCloseOperation(2);

      try{
    FileInputStream fstream = new FileInputStream(name); 
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

   
    while((strLine = br.readLine())!= null ){
    	if (strLine.trim().length() != 0){
    		System.out.println(strLine);
    		count++;
    	}else{
    		count2++;
    	}
    }
    System.out.println("number of lines:" + count);
    System.out.println("number of lines:" + count2);
   
    in.close();
    }catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
    fr.repaint();
}
}

mr tong1, thanks for the help.

I cant seem to run your code in eclipse in line 11 because it says the constructor file dialog is ambiguous.

also, i have modified my code:

import java.awt.Container;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class FileBrowse extends JFrame {

private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(20);
private JButton approve = new JButton("Ok");


public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);

browseSwing.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent arg0) {
		onBrowseSwing();
	}
});


Container container = getContentPane();
container.setLayout(new GridLayout(0, 1));
container.add(browseSwing);
container.add(textField);
container.add(approve);

pack();
}

protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}

public void fileRead(String input){
	try{
	    // Open the file that is the first
	    // command line parameter
	    FileInputStream fstream = new FileInputStream(input);
	    // Get the object of DataInputStream
	    DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
	    String strLine;
	    int count = 0;
	    int count2 = 0;
	    //Read File Line By Line
	    while((strLine = br.readLine())!= null ){
	    	if (strLine.trim().length() != 0){
	    		count++;
	    	}else{
	    		count2++;
	    	}
	    }
	    System.out.println("-------Lines Of COdes-------");
	    System.out.println("number of lines:" + count);
	    System.out.println("number of blank lines:" + count2);
	    //Close the input stream
	    in.close();
	    }catch (Exception e){//Catch exception if any
	      System.err.println("Error: " + e.getMessage());
	    }


}


public static void main(String[] args) {
new FileBrowse().show();

}
}

it has some flaws though. the swing box doesn't exit. it should exit when you click ok. also, it should read the lines when the ok button is click. not when the textfield is filled that it automatically read the lines and prints in the console.

what do i need to do?

ezkonekgal ,thank you for your reply. I have checked and tested your code.
(1) You use JFileChooser which seems better than FileDialog which I use currently (because, as you reported, eclipse complains about the constructor I wrote).
(2) May I suggest you delete the "OK" button which is useless.
(3) Your code runs correctly. I have replaced your LayoutManager by FlowLayout so that components show up properly.
Attached please find the modified code. It runs correctly in my machine.

Edited 6 Years Ago by tong1: n/a

Attachments
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class FileBrowse extends JFrame {

private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");


public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);

browseSwing.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource()==browseSwing)
		onBrowseSwing();
		}});


Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);

//pack();
}

protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}

public void fileRead(String input){
	try{
	    // Open the file that is the first
	    // command line parameter
	    FileInputStream fstream = new FileInputStream(input);
	    // Get the object of DataInputStream
	    DataInputStream in = new DataInputStream(fstream);
	        BufferedReader br = new BufferedReader(new InputStreamReader(in));
	    String strLine;
	    int count = 0;
	    int count2 = 0;
	    //Read File Line By Line
	    while((strLine = br.readLine())!= null ){
	    	if (strLine.trim().length() != 0){
	    		count++;
	    	}else{
	    		count2++;
	    	}
	    }
	    System.out.println("-------Lines Of COdes-------");
	    System.out.println("number of lines:" + count);
	    System.out.println("number of blank lines:" + count2);
	    //Close the input stream
	    in.close();
	    }catch (Exception e){//Catch exception if any
	      System.err.println("Error: " + e.getMessage());
	    }


}


public static void main(String[] args) {
new FileBrowse().setVisible(true);

}
}

Mr tong1, id like to ask why your code wouldn't run. I'd like to see your work. Also, I like the neatness of your code.

Thank you for your "Why". I found I sent you a wrong version. In line code 11 if you put:

FileDialog fd = new FileDialog(null , "Open a document", FileDialog.LOAD);

you will have the error message: "the constructor file dialog is ambiguous"
However, the line of code 11:

FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD);

will pass compiling. Therefore, we should emphasize:
For the first argument "Frame parent" of the FileDialog constroctor one should use "this" indicating the parent Frame is the current object.

Edited 6 Years Ago by tong1: n/a

Mr. Tong1, the code now runs, and for me, i like it much better than how we did it. I like how it resembles like in windows when you would browse for a file.

Thanks for your help. :)

Mr Tong1, i was wondering.. Could it be possible to restrict file to be choosen by the fileDialog.. like wen the dialog opens.. since the program will read lines of code... could i restrict it to accept .java files and .txt files?

can you write code to read from file the count the LOC with out comment and blank

Comments
Please do not wake a dead thread. Let it rest in peace.
This question has already been answered. Start a new discussion instead.