09.12.2011

Java programming pt. 12 count words within a .java file

The following program counts how many times specific Java words appear in the program itself.

import java.io.*;
import java.util.*;

public class Program {

public static void main (String[] args) throws Exception {

String[] keywords = {"import", "public", "for", "if", "else",
"class", "static", "throws", "while", "new"};

int[] index = new int[keywords.length];

BufferedReader bf = new BufferedReader(new FileReader ("Program.java"));

String text = "", line;

while ((line = bf.readLine()) != null) {
text += line + "\n";
}

StringTokenizer st = new StringTokenizer(text);

while (st.hasMoreTokens()) {

String word = st.nextToken();

for (int i = 0; i < keywords.length; ++i) {

if (word.equals(keywords[i])) {

index[i]++;
}

} // end for

} // end while

for (int i = 0; i < keywords.length; ++i) {
System.out.println(keywords[i] + ": " + index[i]);
} // end for

} // end main
} // end class

The result (what you see in the console):

import: 2
public: 2
for: 4
if: 1
else: 0
class: 2
static: 1
throws: 1
while: 3
new: 3

Java programming pt. 11 letters triangle
09.12.2011

The following code snippets show how to get a triangle of capitals and lowercase letters like this one: A b c D E F g h i j K L M N O p q r s t u V W X Y Z A B c d e f g h i j K [...]

Java programming pt. 10 multiplication table
06.12.2011

The following code will print out the multiplication table until 100 by using a for-statement. import javax.swing.*; import java.lang.*; import java.text.*; public class MultiplicationTable { public static void main (String[] args) { // variable declaration int result = 0; String textResult = “”; DecimalFormat resultOutput = new DecimalFormat(“000″); // loop for (int i=1; i<=10; i++) [...]




Welcome to ULVEN.ORG. I'm a Bachelor of Informatics student and this is my blog where I record my progress towards becomming a programmer, web developer and designer. I prefer PHP, CSS3, java and Python.