Information

08/15/11

Home
CMPT 125
CMPT 110
CMPT 210
CMPT 260
Information
Photo Gallery

 

I will be using this page to inform you of writing documents, tutorials and other help aids as the semester goes on.
 
bulletComputer Technology Curriculum Work Sheet
bulletCode Examples

Create Stub, If Else, Comparison Operators, Conditional, Switch Case, Do While, Button Array, Sound in an Application

Writing to a File, Reading from a File, Reading the Contents of a Zipped File

   
   
   

Create a Stub or Outline with Methods and Variables to be used.  Compile and correct errors

// Program stub 2 Page 226


import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class CommStub2
{
public static void main(String[] args)
{
//declare class variables
double dollars, answer;
int empCode;

//Call methods
dollars = getSales();
}

//The getSales() method asks the user to input a dollar amount and validates it.
public static double getSales()
{
//declare method variables
double sales = 0.0;
boolean done = false;



return sales;
}
}

If Else Example

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

int testscore = -96;
char grade;

if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

Comparison Operators

class ComparisonDemo {

public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}

Conditional

class ConditionalDemo1 {

public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 3)) System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1");

}
}

Switch Case

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

int month = 3;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}

Do While

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}

Button Array

//Button Array
//Wendy Plourde
//3/24/2008
//A base for Task 3 a Tic Tack Toe Game using a button Array


import java.awt.*;
import java.awt.event.*;
//import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class TicTacToeLayout extends Frame
{
private Button keys[];
private Panel keypad;

Buttonup butt = new Buttonup();



public TicTacToeLayout()
{

// construct components and initialize beginning values

keypad = new Panel();
keys = new Button[10];


// construct and assign captions to the Buttons
for (int i=0; i<=9; i++)
keys[i] = new Button(String.valueOf(i));


// set Frame and keypad layout to grid layout
setLayout(new BorderLayout());
keypad.setLayout(new GridLayout(3,3,10,10));

for (int i=1; i<=3; i++) // 1,2,3
keypad.add(keys[i]);

for (int i=4; i<=6; i++) // 4, 5, 6
keypad.add(keys[i]);


for (int i=7; i<=9; i++) // 7,8,9
keypad.add(keys[i]);

add(keypad, BorderLayout.CENTER);

} // end of constructor method

public static void main(String args[])
{
// set frame properties
TicTacToeLayout f = new TicTacToeLayout();
f.setTitle("Button Array");
f.setBounds(200,200,300,300);
f.setVisible(true);

} // end of main


}

Sound in an Application

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import sun.audio.*;
import java.io.*;


public class Sound extends JFrame implements ActionListener {

public Sound() {



setSize(200,130);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = getContentPane();
FlowLayout flo = new FlowLayout();
pane.setLayout(flo);
JButton btn = new JButton("Press");
pane.add(btn);
btn.addActionListener(this);
setContentPane(pane);
setVisible(true);
}

public void actionPerformed(ActionEvent event) {

AudioPlayer p = AudioPlayer.player;

String source = event.getActionCommand();

if (source == "Press") {

try{
AudioStream as =
new AudioStream(new FileInputStream("cork.wav"));
p.start(as);
}
catch(IOException err){
err.printStackTrace();
}


}
else
{
}
}

public static void main(String[] arguments) {
Sound sn = new Sound();
}
}

Writing to a File

/*
*
* FileOutputDemo
*
* Demonstration of FileOutputStream and
* PrintStream classes
*
*/

import java.io.*;

class FileOutputDemo
{

public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object

try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file and more stuff too!!!!!!!!!!");
p.println ("And what will this look like in myfile.txt????????");

p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}

Reading from a File

import java.io.*;

public class FileReading
{
// Main method
public static void main (String args[])
{
// Stream to read file
FileInputStream fin;

try
{
// Open an input stream
fin = new FileInputStream ("myfile.txt");

// Reads two lines of text
System.out.println( new DataInputStream(fin).readLine() );
System.out.println( new DataInputStream(fin).readLine() );

// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read from file");
System.exit(-1);
}
}
}

Reading the Contents of a Zipped File

import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import java.io.*;

/**
* Reads GZIP, Zip, and Jar files and outputs their content to the console.
*/

class Zip {
public static void main(String[] args) {
String fileName = args[0];

System.out.println("contents of " + fileName + "...");

if (fileName.endsWith(".gz")) {
readGZIPFile(fileName);

} else if (fileName.endsWith(".zip")) {
readZipFile(fileName);

} else if (fileName.endsWith(".jar")) {
readJarFile(fileName);

}
}
/**
* Reads a GZIP file and dumps the contents to the console.
*/
private static void readGZIPFile(String fileName) {
// use BufferedReader to get one line at a time
BufferedReader gzipReader = null;
try {
// simple loop to dump the contents to the console
gzipReader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream(fileName))));
while (gzipReader.ready()) {
System.out.println(gzipReader.readLine());
}
gzipReader.close();
} catch (FileNotFoundException fnfe) {
System.out.println("The file was not found: " + fnfe.getMessage());
} catch (IOException ioe) {
System.out.println("An IOException occurred: " + ioe.getMessage());
} finally {
if (gzipReader != null) {
try { gzipReader.close(); } catch (IOException ioe) {}
}
}
}

/**
* Reads a Zip file, iterating through each entry and dumping the contents
* to the console.
*/
private static void readZipFile(String fileName) {
ZipFile zipFile = null;
try {
// ZipFile offers an Enumeration of all the files in the Zip file
zipFile = new ZipFile(fileName);
for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
ZipEntry zipEntry = (ZipEntry) e.nextElement();
System.out.println(zipEntry.getName() + " contains:");
// use BufferedReader to get one line at a time
BufferedReader zipReader = new BufferedReader(
new InputStreamReader(zipFile.getInputStream(zipEntry)));
while (zipReader.ready()) {
System.out.println(zipReader.readLine());
}
zipReader.close();
}
} catch (IOException ioe) {
System.out.println("An IOException occurred: " + ioe.getMessage());
} finally {
if (zipFile != null) {
try { zipFile.close(); } catch (IOException ioe) {}
}
}
}

/**
* Reads a Jar file, displaying the attributes in its manifest and dumping
* the contents of each file contained to the console.
*/
private static void readJarFile(String fileName) {
JarFile jarFile = null;
try {
// JarFile extends ZipFile and adds manifest information
jarFile = new JarFile(fileName);
if (jarFile.getManifest() != null) {
System.out.println("Manifest Main Attributes:");
Iterator iter =
jarFile.getManifest().getMainAttributes().keySet().iterator();
while (iter.hasNext()) {
Attributes.Name attribute = (Attributes.Name) iter.next();
System.out.println(attribute + " : " +
jarFile.getManifest().getMainAttributes().getValue(attribute));
}
System.out.println();
}
// use the Enumeration to dump the contents of each file to the console
System.out.println("Jar file entries:");
for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
JarEntry jarEntry = (JarEntry) e.nextElement();
if (!jarEntry.isDirectory()) {
System.out.println(jarEntry.getName() + " contains:");
BufferedReader jarReader = new BufferedReader(
new InputStreamReader(jarFile.getInputStream(jarEntry)));
while (jarReader.ready()) {
System.out.println(jarReader.readLine());
}
jarReader.close();
}
}
} catch (IOException ioe) {
System.out.println("An IOException occurred: " + ioe.getMessage());
} finally {
if (jarFile != null) {
try { jarFile.close(); } catch (IOException ioe) {}
}
}
}

}


 

Home | CMPT 125 | CMPT 110 | CMPT 210 | CMPT 260 | Information | Photo Gallery

This site was last updated 03/29/10