Number of lines in a method
Hi all,
can you please tell me how to get the number of lines in each method in a java file.
class test
public void method(){
sop()...
sop()...
In that above class, the number of lines in "method" is 2.
is there any api in java which will return us the number of lines in each method in a java file?
Please suggest me..
-I was wondering about some crazy bytecode reader.javap?
-I agree it's not the best solution, but going for 100% accuracy wasn't the aim here :)Please understand that I'm not criticizing your attempt, but rather that the OP's requirements are far too vague to provide any useful advice.
-How does it not deal with loops/code blocks? (case statements maybe as I forgot ":")Example:
String method =
"void method() {\n" +
" for (int i = 0; i < 1; i++) {\n" +
" System.out.println(this.toString());\n" +
" }\n" +
int expectedLineCount = 3; // possibly, based on what the OP's indicated so far...
int actualLineCount = method.split("[;{}]").length; // per your example
assert expectedLineCount != actualLineCount;~
Similar Messages
-
Java Program+To count the number of lines in a method excluding comments???
Hi friends
can u plz help me out, the java program is counting the number of lines in a method excluding comments.
The first thing is how to identify a method, then there can be an inner method inside the parent method,
Please friends its urgent
Bye
SandyThere's no such thing as an inner method in Java. You can either write the code yourself to parse Java source, or maybe something like ANTLR can do it.
-
Max number of lines in method.
Hi,
Syntatically a method can span for any number of lines, but is there
a limit on number of lines in a method so that it conforms to java code
conventions. Could not find anything about the number of lines in Sun java code conventions doc.
Thanks
DeepakThe whole point is write a method that does only one thing. The hard thing is to determine what one thing is. A method which only
does one thing can also become long, and needs to be broken down
to several small methods. A method name is a very good documentation
(unless you use random method names)I also use one of my few rules of thumb here:
rule#5059723586: if you can't describe in one sentence, using
appropriate detail, what a method does, it needs to be refactored to
at least two methods. repeat rule#5059723586 as long as applicable.
rule#5059723586B: The verbs and nouns of the 'appropriate detail'
mentioned in rule#5059723586 must refer to members, parameters
or other methods (see also rule# 5059723586)
kind regards,
Jos ;-) -
How to count number of lines inside methods() using the Doclet API
Wrote a custom doclet using the [Doclet API|http://java.sun.com/j2se/1.3/docs/tooldocs/javadoc/doclet/index.html ] .
The purpose for the doclet is to load Java source files and create stubs (which are identical Java source files but do not contain any method implementation details).
Instead, the method implementation details need to be replaced with blank lines...
public class MyDoclet {
private static String TAB = "\t";
public static boolean start(RootDoc root) {
ClassDoc[] classes = root.classes();
// Parse through class or interface
for (ClassDoc clazz : classes) {
Type superClass = clazz.superclassType();
// Print Methods
MethodDoc[] methods = clazz.methods();
for (MethodDoc method : methods) {
Parameter[] parameters = method.parameters();
println();
if (!method.isPrivate()) {
print(TAB + method.modifiers() + " "
+ method.returnType().simpleTypeName() + " " + method.name());
print("(");
for (int i=0; i < parameters.length; i++) {
Parameter parameter = (Parameter) parameters;
print(parameter.type().simpleTypeName() + " " + parameter.name());
if (i != parameters.length - 1) {
print(", ");
print(")");
println(" {");
println("\n");
println(TAB + "}");
return true;
As one can see, I am just creating the method and placing the opening and closing curly braces (along with a new \n line escape sequence, in between).
Am not really that familiar with the Doclet API...
Question(s):
(1) What is the best way to figure out how many lines of code are inside each method and then use a for loop to insert the exact same number of blank lines inside the methods?
(2) Is there a way to do it using the com.sun.javadoc.SourcePosition.line() method?
Would really appreciate it if someone could help me because this is an important requirement (hence the 10 Duke Stars).
Happy coding to all,
MikeThis is not possible using the Doclet API, because JavaDoc does not store any information regarding implementation detail. Although MethodDoc#position will give you the line where the method is declared, there is no way to determine where the method body starts and ends.
If you need that much information, maybe you would be better of using a tool such as Eclipse's Abstract Syntax Tree parser. AST will provide you with line numbers for each code expression, hence it is relatively easy to compute the first and last line in a method body. -
Effiecient method to get number of lines in a JEditorPane
My Computer Science class has a major grade project to complete by Dec. 15. For my project I've decided to make a tabbed Java IDE with save, open, compile, run, and some font options. Due to the need to make Java use the command prompt to compile and run, it will be Windows specific.
Now, next to my JEditorPane I want to put a JPanel with a GridLayout full of JLabels that will hold the line numbers. I'm having a small problem getting the precise number of lines though. Due to the nature of JEditorPane, I can't just count the number of newline characters in the JEditorPane. I've tried to use a Scanner to go through the text and find all instances of the string "<p style=\"margin-top: 0\">" but because the JEditorPane doesn't make a new <p> tag until text is entered into a new line, this only works some of the time.
Does anyone know of a way I can effectively and efficiently find the number of lines in the JEditorPane at any given time?
Message was edited by:
TheGuy@YourWindowSwing related questions should be posted in the Swing forum.
Normally for a text editor you would use a JTextArea for simple text or a JTextPane if you plan on doing syntax highlighting. JEditorPane is typically used to display HTML files.
If you search the Swing forum using "utextcomponent" you will find my class that has methods that might be handy for what you want. -
Count the number of Lines with in a method
I am trying to write a program that will report back the number of methods/types/names and proxies as well as the number of lines of code in each method... I can not figure out how to count each methods line of code separately thanks. each method is commented by
/* PROXY proxyname type */
/* METHOD method name*/
public class Assignment3
private static BufferedReader userInput = new BufferedReader (new InputStreamReader (System.in));
* @param args
* @throws IOException
* @param args
* @throws IOException
public static void main(String[] args) throws IOException
System.out.print("Enter the .java file name: ");
String input = userInput.readLine();
while (!input.equalsIgnoreCase("stop"))
System.out.println("Total Number of Lines: " + LOC(input) + "\n" + Method(input) + "\n" + Type(input));
System.out.print("\nEnter file name to search again or \"stop\" to terminate the program: ");
input = userInput.readLine();
public static int LOC(String inputFile) throws IOException, FileNotFoundException
int numLines = 0;
try
FileReader FileIn = new FileReader(inputFile);
Scanner scanLines = new Scanner (FileIn);
String line;
while (scanLines.hasNext())
line = scanLines.nextLine();
if (line.startsWith("/*"))
numLines--;
else if(!line.equals(" "))
numLines++;
FileIn.close();
catch(IOException IOE)
System.out.println("\nFile Not Found!");
return numLines;
public static int MethodLOC(String inputFile) throws IOException, FileNotFoundException
File FileIn = new File(inputFile);
Scanner scanLines = new Scanner (FileIn);
String line = null;
int methodLOC = 0;
while(scanLines.hasNext())
line = scanLines.nextLine();
if(!line.contains("/*"))
StringTokenizer st = new StringTokenizer(line, "\n");
methodLOC = st.countTokens();
return methodLOC;
public static String Method(String inputFile) throws IOException, FileNotFoundException
String line = null;
String name = null;
String info = null;
File FileIn = new File(inputFile);
Scanner scanLines = new Scanner (FileIn);
while(scanLines.hasNext())
line = scanLines.nextLine();
if(line.contains("METHOD"))
StringTokenizer st = new StringTokenizer(line, " ");
String proxy = st.nextToken();
String method = st.nextToken();
name = st.nextToken();
info = "Name of Method: " + name;
return info;
public static String Type(String inputFile) throws IOException, FileNotFoundException
String line = null;
String name = null;
String info = null;
String count = null;
File FileIn = new File(inputFile);
Scanner scanLines = new Scanner (FileIn);
while(scanLines.hasNext())
if(line.contains("PROXY"))
StringTokenizer st = new StringTokenizer(line, " ");
String proxy = st.nextToken();
String method = st.nextToken();
name = st.nextToken();
String type = st.nextToken();
info = "Name of Proxy: " + name + "\n" + "Type of Proxy: " + type;
count = info;
return count;
}Iterate through the lines and count the opening and closing curly braces. Whenever you see an opening one, increase the counter, when you see a closing one, decrease the counter. When the counter hits 0 again, you reached the end of the method.
I assume you know how to count lines while moving through a text line by line. -
ALV_GRID How to get number of lines after filted applyed?
Hi, all!
The task is to display title in alv_grid like
"N records selected (X records on the screen)".
It means, N records in dataset and X records displayed after filter applyed by user.
But i can't get number of lines after filter applyed from the alv_grid.
Can anybody help me?
Thanks & regards,
KonstantinHi,
If it goes through PBO/PAI cycle after user sets the filter then in your PBO call method get_filtered_entries of CL_GUI_ALV_GRID and then do a describe statement on the table.
Number of entries in your grid table - number of entries in this filtered entries table will give you the displayed entries after the filter is set.
If it does not go through PBO/PAI cycle then register for after_user_command and I think the fcode for filter is '&FILTER' and code for the above logic in your handler method..
Hope this helps..
Sri -
How to get the number of lines of a file?
Folks:
Is there a way to get the number of lines of a text file? I don't know if there is an existing method to do that.
Thanks a lot.HI
I found some solution
other than increment loop and all
here is the code it might helpful to u
//returns the number of lines in a file
//author : Ravindra S
//Symphony software Hyderabad
try
RandomAccessFile randFile = new RandomAccessFile(csvFile,"r");
long lastRec=randFile.length();
randFile.close();
FileReader fileRead = new FileReader(csvFile);
LineNumberReader lineRead = new LineNumberReader(fileRead);
lineRead.skip(lastRec);
countRec=lineRead.getLineNumber()-1;
fileRead.close();
lineRead.close();
catch(IOException e) -
Is there a method that returns the number of lines in a text file? I'm trying to make an array of arrays, with each inner array holding 4 strings from 4 consecutive lines from a file, and the outer array holding every one of those arrays that are possible in the file. I can't anticipate the amount of 4-line blocks im going to have tho, so i need something that returns the number of lines available and divides that by four. I'll then populate the outer array by looping that many times. If any of that made sense...
Is there a method that returns the number of lines in
a text file? I'm trying to make an array of arrays,
with each inner array holding 4 strings from 4
consecutive lines from a file, and the outer array
holding every one of those arrays that are possible
in the file. I can't anticipate the amount of 4-line
blocks im going to have tho, so i need something that
returns the number of lines available and divides
that by four. I'll then populate the outer array by
looping that many times. If any of that made sense...You would do better to use java.util.List implementations such as ArrayList and LinkedList then you don't need to know the number of lines. -
Limit number of lines in a text editor
Hello.
In my program, i'm creating a text zone and i need to limit the data users will put in this zone.
To create that, i'm using the object cl_gui_textedit. I've looked in the methods of this object but i wasn't able to find one that will limit the number of lines of the text editor.
Did i miss it ? Does anybody knows how i can for example limit the input zone to 5 lines ?
Thanks for your help.
Here's my code
IF g_editor IS INITIAL.
* Instanciation du container pour la zone de texte
CREATE OBJECT g_textedit_custom_container
EXPORTING
container_name = 'TEXTEDITOR'
EXCEPTIONS
cntl_error = 1
cntl_system_error = 2
create_error = 3
lifetime_error = 4
lifetime_dynpro_dynpro_link = 5.
IF sy-subrc NE 0.
* add your handling
ENDIF.
* Création de la zone d'édition du texte
CREATE OBJECT g_editor
EXPORTING
parent = g_textedit_custom_container
wordwrap_mode = cl_gui_textedit=>wordwrap_at_fixed_position
wordwrap_position = 68
wordwrap_to_linebreak_mode = cl_gui_textedit=>true.
ENDIF.I just notice there is a method SET_HEIGHT but this one is implemented in CL_GUI_CONTROL.
I tried this :
CALL METHOD g_editor->set_height
EXPORTING height = w_height.
But in fact, i never enter the method.
Do i have to create a CL_GUI_CONTROL object ? If yes, how do i link it to the CL_GUI_TEXTEDIT.
Sorry if some questions mays seem obvious. It's my first object abap program. -
Total number of lines of code in a class.
Dear Experts,
Given a class, I want to find out the total number of lines of code in all of its methods. Following sub-parts are derived.
1. Find out all the methods of the class
2. Find out the number of lines for each of these methods and finally add the total number.
Can you kindly let me know how I can do this? Thanks a lot !
Best Regards, VikramBe aware that a 2D array is an array of arrays, which don't necessarily have to be the same length. e.g.int[][] a = new int[2][];
a[0] = new int[10];
a[1] = new int[20];
/* a.length == 2
a[0].length == 10
a[1].length == 20*/ -
Count the number of lines in a txt file
I need to count the number of lines in a txt file, but I can't do it using readLine(). This is because the txt file is double spaced. readLine() returns null even if it is not the end of the file. thanks for the help
I need to count the number of lines in a txt file,
but I can't do it using readLine(). Then just compare each single byte or char to the newline (code 10).
This is because the txt file is double spaced. readLine() returns
null even if it is not the end of the file.Errm what? What do you mean by "double spaced"? Method readLine() should only return null if there's nothing more to read. -
Counting the number of lines for each procedure in a package
Hi,
I would like to write a query on USER_SOURCE that can display the number of code lines for each procedure/function in a package.
Is it possible to write such a query? Maybe by using analytical functions?
for example in the following example i would like to count the lines between "PROCEDURE proc1 IS" and "END proc1;" and between "PROCEDURE proc2 IS" and "END proc2;"
SQL> select text from user_source where name='PKG_TEST' and type='PACKAGE BODY';
TEXT
PACKAGE BODY PKG_TEST IS
PROCEDURE proc1 IS
BEGIN
update t1 set EDITION_NAME = 'AAAAAAA';
commit;
END proc1;
PROCEDURE proc2 IS
BEGIN
update t1 set EDITION_NAME = 'AAAAAAA';
commit;
END proc2;
END PKG_TEST;thanks for helpingonedbguru wrote:
Hopefully some idiot manager isn't trying to use this sort of thing to base their decisions on developer productivity. If so, they ARE idiots. Number of code lines NEVER, EVER, EVER!!! translates into an efficient application. If I were paid by the line, my code would look like:
select
1
from
dual
Based on the idiocy of this method of determining "performance" I would get paid $5.00 at $1.00/line. And trust me, I saw this back in the 80's and 90's and saw similar idiotic code and had to clean up the mess. Most of it wasn't efficient code to start with let alone the number of lines generated.Or the other extreme, when the PHB firmly believed that execution efficiency was gained by reducing the number of lines of code. So instead of nicely formatted, easy to read code:
*GET NEXT ORDER NUMBER
EXEC SQL
SELECT (MAX(ORDER_NUM) + 1)
INTO :NEXT-NUM:IND-NULL
FROM PART_ORDER
END-EXEC.
IF IND-NULL < 0
MOVE 1 TO NEXT-NUM.
EXEC SQL
INSERT
INTO PART_ORDER
(ORDER_NUM,
ORIGIN_LOC,
ORDER_TYPE,
ORDER_STAT,
CREAT_TIME)
VALUES (:NEXT-NUM,
:LOC, 'R', 'O',
CURRENT TIMESTAMP)
END-EXEC.
MOVE NEXT-NUM TO MASK0.
PERFORM HEADER-PROC THRU HEADER-EXIT.
CREATE-ORDER-EXIT. EXIT. You got this:
*GET NEXT ORDER NUMBER
EXEC SQL SELECT (MAX(ORDER_NUM) + 1) INTO :NEXT-NUM:IND-NULL FROM
PART_ORDER END-EXEC. IF IND-NULL < 0 MOVE 1 TO NEXT-NUM. EXEC SQL INSERT
INTO PART_ORDER (ORDER_NUM, ORIGIN_LOC, ORDER_TYPE, ORDER_STAT,
CREAT_TIME) VALUES (:NEXT-NUM, :LOC, 'R', 'O', CURRENT TIMESTAMP)
END-EXEC. MOVE NEXT-NUM TO MASK0. PERFORM HEADER-PROC THRU HEADER-EXIT.
CREATE-ORDER-EXIT. EXIT. Oh, wait! See the same thing all the time in this forum ... not because someone thinks fewer lines = faster code, but simply because people are sloppy.
INSERT INTO PART_ORDER(ORDER_NUM,ORIGIN_LOC,ORDER_TYPE,ORDER_STAT,CREAT_TIME) VALUES (:NEXT-NUM,:LOC, 'R', 'O',CURRENT TIMESTAMP) ; -
Hello ,
I need a hitlist of customer programms with the most numbers of lines, or programmes with more than 5.000 lines of coding.
Is there a table ?
Which table holds the coding ?
Thanks for any answer you know.
Cheers
SimoneHello Simone
Below you find a variation of my previous report adjusted for reading function groups:
*& Report ZUS_SDN_ABAP_SOURCE_CODE_1
*& Thread: Number of lines of an ABAP
*& <a class="jive_macro jive_macro_thread" href="" __jive_macro_name="thread" modifiedtitle="true" __default_attr="817091"></a>
REPORT zus_sdn_abap_source_code_1.
TYPE-POOLS: sedi, suni.
TABLES: tlibg.
TABLES: tfdir.
DATA: go_source TYPE REF TO cl_wb_source,
gs_trkey TYPE trkey,
gt_functab TYPE suni_functab,
gs_func LIKE LINE OF gt_functab,
gd_repid TYPE sy-repid,
gt_source TYPE sedi_source,
gt_linenumbers TYPE sedi_linenumbers,
gd_msg TYPE bapi_msg.
PARAMETERS:
p_fugr TYPE tlibg-area DEFAULT 'ZUS_SDN_ALV_SCREEN'.
START-OF-SELECTION.
CALL FUNCTION 'FUNCTION_INCLUDE_INFO'
IMPORTING
functab = gt_functab
* NAMESPACE =
* PNAME =
CHANGING
* FUNCNAME =
group = p_fugr
* INCLUDE =
EXCEPTIONS
function_not_exists = 1
include_not_exists = 2
group_not_exists = 3
no_selections = 4
no_function_include = 5
OTHERS = 6.
IF sy-subrc NE 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
RETURN.
ENDIF.
READ TABLE gt_functab INTO gs_func INDEX 1. " just read 1st fm
CLEAR: gs_trkey.
SELECT SINGLE * FROM appl_func INTO CORRESPONDING FIELDS OF gs_trkey
WHERE obj_name = p_fugr.
CHECK ( syst-subrc = 0 ).
** gs_trkey-devclass = 'ZUS_SDN1'.
gs_trkey-obj_type = 'FUGR'.
** gs_trkey-obj_name = p_fugr.
gs_trkey-sub_type = 'FUNC'.
gs_trkey-sub_name = gs_func-funcname.
gd_repid = gs_func-funcincl. " include of fm
CREATE OBJECT go_source
EXPORTING
transport_key = gs_trkey
* source_name = 'ZUS_SDN_ABAP_SOURCE_CODE'
* modification_mode =
* abap_editor =
* method_key =
CALL METHOD go_source->read_source
EXPORTING
* status = SPACE
* toggle_enh_status = SPACE
source_name = gd_repid
* initialize_edit_control = ' '
* load_from_temp_storage = 'X'
* load_from_temp_storage_uncond = SPACE
* with_conversion = 'X'
* mode =
* with_enhancements = 'X'
* insert_impl_enh_points = ' '
* IMPORTING
* source_tab =
* CHANGING
* mod_instance =
EXCEPTIONS
cancelled = 1
not_found = 2
read_protected = 3
enhancement_locked = 4
OTHERS = 5.
IF sy-subrc NE 0.
MESSAGE ID sy-msgid TYPE 'I' NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
RETURN.
ENDIF.
CALL METHOD go_source->get_source_tab
* EXPORTING
* use_attribute = space
* use_control = space
IMPORTING
SOURCE = gt_source.
** CALL METHOD go_source->get_linenumbers
** IMPORTING
** linenum = gt_linenumbers.
** DESCRIBE TABLE gt_linenumbers.
DESCRIBE TABLE gt_source.
IF ( syst-tfill > 50 ).
CONCATENATE 'FB' gs_func-funcname
'contains > 50 coding lines'
INTO gd_msg SEPARATED BY space.
MESSAGE gd_msg TYPE 'I'.
ENDIF.
END-OF-SELECTION.
Regards
Uwe -
How do i detect the maximum number of lines
Situation:
I have a textfield that displays about 8 lines of text before
the content would need to be scrolled to view the remaining
content.
Question
Rather than having some ActionScript that is constantly
trying to scroll the field, how do i detect the following.
How do i determine the maximum number of lines that may be
displayed in a textField (or any type of text field) before
scrolling would be needed?
Please specify the method. Thank you.When tracing the output using the bottomScroll, it only tells
me how many liines I have output to the textfiedl, it does not tell
me how many lines the textfield can hold.
How do I determine how many lines a textfield can
hold?
Maybe you are looking for
-
Open Purchase Orders not considered as requirement for MRP Run
Hi , We are facing a issue of Open Purchase orders not appeared in Stock requirements list and also it is not considered as requirement for MRP Run against reservation. As aresult for a reservation demand of 10 units we are ending with Open POs 10 un
-
Daisy Chaining Thunderbolt Monitors
I see that a 15 inch Macbook can drive two daisy chained Thunderbolt monitors. Can a post 2012 Air Book also do this? Going in another direction, if i use the 15 Inch Macbook with a thunderbolt monitor, can i daisy chain in a Cinema Display to that?
-
Need to populate text/ref fields for docs generated by allocation cycles
When executing distribution or assessment cycles the doc header text, reference field and line item text are all left blank in the generated accounting document. We would like to populate these fields with some reference to the cycle or segment name
-
Interaction ESS - Webdynpro - Websphere portal
Hi all, a question please if you can help me: Could Websphere Portal interact with ESS through the URL address of its WebDynpro pages ? do you know something about this argument ? I know that in the old version, it was easy for a non-SAP portal to wo
-
How to separate business from personnal in mail
I'm using 5 different account in mail, some are for business, some for personal use. Sometime, a business mail is send from a personal account by error and vise versa. Is it possible to have two mail application? One for business and one for personal