Templates for writing Java programs

These are all console based programs, no graphics at all (though you could use JOptionPanes).

Writing a simple application

The only things that can be outside a class are in pink below:


package myPackage;
//comments can go here
import java.util.Something;
import java.IO.SomethingElse;

public class AppName {
	public static void main(String[] args) {
	
		//code goes here
		
	} //end of main
} //end of class

Note: (1) This file must be saved as AppName.java (actually, you'ld rename the class here to match your java file
(2) Java always looks for a public static function called main which it runs first in order to start the application.

Writing a simple application with methods and global variables

public class AppName {

	//global variables go here
	static int score = 0;

	public static void main(String[] args) {
		//code goes here
	} 

	static void method1() {
		//code goes here
	}

} 

Note:
global variables have to be static
methods will have to be static
methods don't need to be public and may return something other than void

Writing a general class

public class Thing extends ____   implements _____
{
	//class variables (also called static variables )

	//instance variables (normally most are private) (also called fields)
	
	//static functions  (applications need "main" here)  (if main is in the same class, put it first)
	
	//constructors (constructor functions)

	//other instance functions (both public and private ones) (functions are called methods in Java)
	
	//inner classes - used for small things (like ActionListeners) or for overriding graphics classes 
	(eg. making your own JPanel, JButton)

}

//any variables declared inside methods and code blocks are local variables

Using scanner to read from files

Note: You can use this program to process each line in a file.

import java.util.Scanner;

public class ReadTextFile
{
	public static void main(String[] args)
	{

		File file = new File("/home/flynn/Desktop/input.txt");
		Scanner sc = new Scanner(file);
		while(sc.hasNext()) {
			line = sc.next();
			System.out.println(line); // or run: processLine(line);
			if(line.length()==0) continue;
		}

		sc.close();
	}
}

/*
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
*/

Using buffered readers to read from files

Note: You can use this program to process each line or each letter in a file.

import java.io.*; 
//import java.text.NumberFormat;

/**************************************************************************
* TEMPLATE to show how to open and read from a text file line by line.    *
* ** It does NOT show how to write to a file.                             *
*                                                                         *
* Use this template to count the number of each letter (A-Z) in a large   *
* text file.                                                              *
* You'll need to add in other variables where you can store the totals.   *
* It is possible to do it in an array.                                    *
* It can be very quick if understand whoe to change the char to an int.   *
**************************************************************************/

public class LetterFreq
{
	public static void main(String[] args)
	{
		/******************** Open file *******************/
		String filename = "c:\\boot.ini";	//Do you know why there are two \\ ?
		BufferedReader bfIn = null;
		try	{
			File file = new File(filename);
			bfIn = new BufferedReader( new FileReader(file) );
		}
		catch (FileNotFoundException e)	{
			System.out.println("The file doesn't exist.");
			System.exit(0);
		}
			
		/*******loop through file reading each line ********/
		while(true) {
			String line = null;	//put string in here so I'm not making vast numbers of immutable strings
			char letter = '\0';	//this is how you make an empty character
			int lettnum;			
			
			/********** read in a line ***********/
			try	{
				line = bfIn.readLine(); //EOF will set line to NULL
			}
			catch (IOException e) {
				System.out.println("Error reading from file");
				System.exit(0);
			}
			
			if (line == null) break; //check for end of file before doing anything
			
			//DEBUG. You probably want to make the line uppercase for use below.
			System.out.println(line.toUpperCase() + " " + line.length());
			
			/* >>>>>>>  process each line -- do whatever you want with it. <<<<<<<<<<*/
			//processLine(line);  // use a separate function, or just put the code here
			

			/* >>>>>>> or process each letter <<<<<<<<<<<<<<<<<<<<<<<<<< */
			for (int i = 0 ; i < line.length(); i++ ) {
				letter = line.charAt(i);
				//process the letter here or call a function below
				//processLetter(letter);
			}
		
		} //end of file reading (ie. end of while loop)
		
		/* >>>>> Printout out your results here <<<<<<< */
	


		/********* close file - its a nice thing to do ***********/
		try {
			bfIn.close();
		} catch (IOException e) {
			System.out.println("Can't close file");
			System.out.println(e);
			System.exit(0);
		}
	} //end of main()
	
	static void processLine(String str) {}	//dummy function
	static void processLetter(char c) {}	//dummy function
	
} //end of class