Showing posts with label compsci. Show all posts
Color Spectrum
Thursday, February 04, 2010
I actually do not understand how the colors mix from red to yellow.
//
import java.awt.*;
import javax.swing.*;
/**
* Class spectrum - write a description of the class here
*
* @author (your name)
* @version (a version number)
*/
public class spectrum extends JApplet
{
// instance variables - replace the example below with your own
private int x;
int width, height;
int N = 25; // the number of colors created
Color[] spectrum; // an array of elements, each of type Color
Color[] spectrum2; // another array
/**
* Called by the browser or applet viewer to inform this JApplet that it
* has been loaded into the system. It is always called before the first
* time that the start method is called.
*/
public void init()
{
// this is a workaround for a security conflict with some browsers
// including some versions of Netscape & Internet Explorer which do
// not allow access to the AWT system event queue which JApplets do
// on startup to check access. May not be necessary with your browser.
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
// provide any initialisation necessary for your JApplet
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
// Allocate the arrays; make them "N" elements long
spectrum = new Color[ N ];
spectrum2 = new Color[ N ];
// Generate the colors and store them in the arrays.
for ( int i = 1; i <= N; ++i ) {
// The three numbers passed to the Color() constructor
// are RGB components in the range [0,1].
// The casting to (float) is done so that the divisions will be
// done with floating point numbers, yielding fractional quotients.
// As i goes from 1 to N, this color goes from almost black to white.
spectrum[ i-1 ] = new Color( i/(float)N, i/(float)N, i/(float)N );
// As i goes from 1 to N, this color goes from almost pure blue to pure red.
spectrum2[ i-1 ] = new Color( i/(float)N, 0,(N-i)/(float)N );
}
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* should start its execution. It is called after the init method and
* each time the JApplet is revisited in a Web page.
*/
public void start()
{
// provide any code requred to run each time
// web page is visited
}
/**
* Called by the browser or applet viewer to inform this JApplet that
* it should stop its execution. It is called when the Web page that
* contains this JApplet has been replaced by another page, and also
* just before the JApplet is to be destroyed.
*/
public void stop()
{
// provide any code that needs to be run when page
// is replaced by another page or before JApplet is destroyed
}
/**
* Paint method for applet.
*
* @param g the Graphics object for this applet
*/
public void paint( Graphics g ) {
int step = 90 / N;
for ( int i = 0; i < N; ++i ) {
g.setColor( spectrum[ i ] );
g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 );
g.setColor( spectrum2[ i ] );
g.fillArc( width/3, height/3, 4*width/3, 4*height/3,
90+i*step, step+1 );
}
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* is being reclaimed and that it should destroy any resources that it
* has allocated. The stop method will always be called before destroy.
*/
public void destroy()
{
// provide code to be run when JApplet is about to be destroyed.
}
/**
* Returns information about this applet.
* An applet should override this method to return a String containing
* information about the author, version, and copyright of the JApplet.
*
* @return a String representation of information about this JApplet
*/
public String getAppletInfo()
{
// provide information about the applet
return "Title: \nAuthor: \nA simple applet example description. ";
}
/**
* Returns parameter information about this JApplet.
* Returns information about the parameters than are understood by
this JApplet.
* An applet should override this method to return an array of Strings
* describing these parameters.
* Each element of the array should be a set of three Strings containing
* the name, the type, and a description.
*
* @return a String[] representation of parameter information
about this JApplet
*/
public String[][] getParameterInfo()
{
// provide parameter information about the applet
String paramInfo[][] = {
{"firstParameter", "1-10", "description of first parameter"},
{"status", "boolean", "description of second parameter"},
{"images", "url", "description of third parameter"}
};
return paramInfo;
}
}
//
//
import java.awt.*;
import javax.swing.*;
/**
* Class spectrum - write a description of the class here
*
* @author (your name)
* @version (a version number)
*/
public class spectrum extends JApplet
{
// instance variables - replace the example below with your own
private int x;
int width, height;
int N = 25; // the number of colors created
Color[] spectrum; // an array of elements, each of type Color
Color[] spectrum2; // another array
/**
* Called by the browser or applet viewer to inform this JApplet that it
* has been loaded into the system. It is always called before the first
* time that the start method is called.
*/
public void init()
{
// this is a workaround for a security conflict with some browsers
// including some versions of Netscape & Internet Explorer which do
// not allow access to the AWT system event queue which JApplets do
// on startup to check access. May not be necessary with your browser.
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
// provide any initialisation necessary for your JApplet
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
// Allocate the arrays; make them "N" elements long
spectrum = new Color[ N ];
spectrum2 = new Color[ N ];
// Generate the colors and store them in the arrays.
for ( int i = 1; i <= N; ++i ) {
// The three numbers passed to the Color() constructor
// are RGB components in the range [0,1].
// The casting to (float) is done so that the divisions will be
// done with floating point numbers, yielding fractional quotients.
// As i goes from 1 to N, this color goes from almost black to white.
spectrum[ i-1 ] = new Color( i/(float)N, i/(float)N, i/(float)N );
// As i goes from 1 to N, this color goes from almost pure blue to pure red.
spectrum2[ i-1 ] = new Color( i/(float)N, 0,(N-i)/(float)N );
}
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* should start its execution. It is called after the init method and
* each time the JApplet is revisited in a Web page.
*/
public void start()
{
// provide any code requred to run each time
// web page is visited
}
/**
* Called by the browser or applet viewer to inform this JApplet that
* it should stop its execution. It is called when the Web page that
* contains this JApplet has been replaced by another page, and also
* just before the JApplet is to be destroyed.
*/
public void stop()
{
// provide any code that needs to be run when page
// is replaced by another page or before JApplet is destroyed
}
/**
* Paint method for applet.
*
* @param g the Graphics object for this applet
*/
public void paint( Graphics g ) {
int step = 90 / N;
for ( int i = 0; i < N; ++i ) {
g.setColor( spectrum[ i ] );
g.fillArc( 0, 0, 2*width, 2*height, 90+i*step, step+1 );
g.setColor( spectrum2[ i ] );
g.fillArc( width/3, height/3, 4*width/3, 4*height/3,
90+i*step, step+1 );
}
}
/**
* Called by the browser or applet viewer to inform this JApplet that it
* is being reclaimed and that it should destroy any resources that it
* has allocated. The stop method will always be called before destroy.
*/
public void destroy()
{
// provide code to be run when JApplet is about to be destroyed.
}
/**
* Returns information about this applet.
* An applet should override this method to return a String containing
* information about the author, version, and copyright of the JApplet.
*
* @return a String representation of information about this JApplet
*/
public String getAppletInfo()
{
// provide information about the applet
return "Title: \nAuthor: \nA simple applet example description. ";
}
/**
* Returns parameter information about this JApplet.
* Returns information about the parameters than are understood by
this JApplet.
* An applet should override this method to return an array of Strings
* describing these parameters.
* Each element of the array should be a set of three Strings containing
* the name, the type, and a description.
*
* @return a String[] representation of parameter information
about this JApplet
*/
public String[][] getParameterInfo()
{
// provide parameter information about the applet
String paramInfo[][] = {
{"firstParameter", "1-10", "description of first parameter"},
{"status", "boolean", "description of second parameter"},
{"images", "url", "description of third parameter"}
};
return paramInfo;
}
}
//
AT Machine
Wednesday, December 16, 2009
import java.util.*;
import java.io.*;
public class ATM {
Vector balance;
Vector name;
Vector password;
File file = new File("data.txt");
public ATM(){
balance = new Vector();
name = new Vector();
password = new Vector();
//init();
}
public void init(){
int option = 0;
loadFile();
Scanner in = new Scanner(System.in);
do {
System.out.println("[1] Create new Account");
System.out.println("[2] Access Existing Account");
System.out.println("[3] Exit");
System.out.print("> ");
String input = in.nextLine();
try {
option = Integer.parseInt(input);
} catch (Exception e){
option = 0;
}
if(option > 3 || option < 1){
System.out.println("Invalid input.");
continue;
}
if(option == 1){
create();
}
if(option == 2){
open();
}
} while (option != 3);
in.close();
writeFile();
}
private void create(){
Scanner in = new Scanner(System.in);
System.out.print("Enter Account Name: ");
String actname = in.nextLine();
if(accountSearch(actname)>=0){
System.out.println("Account Already Exists.");
} else {
name.add(actname);
System.out.print("Enter Password: ");
password.add(in.nextLine());
balance.add(0.0);
System.out.println("Account " + name.lastElement() + " created!");
}
in.close();
}
private void open(){
Scanner in = new Scanner(System.in);
System.out.print("Enter Account Name: ");
int accountNumber = accountSearch(in.nextLine());
if(accountNumber >= 0){
System.out.print("Enter Password: ");
if(password.get(accountNumber).equals(in.nextLine())){
int option = 0;
double amount = 0;
do {
System.out.println("[1] Deposit Funds");
System.out.println("[2] Withdraw Funds");
System.out.println("[3] Balance Inquiry");
System.out.println("[4] Exit");
System.out.print("> ");
option = in.nextInt();
if(option > 4 || option < 1){
System.out.println("Invalid input.");
continue;
}
if(option == 1){
deposit(accountNumber);
}
if(option == 2){
withdraw(accountNumber);
}
if(option == 3){
balance(accountNumber);
}
} while (option != 4);
} else {
System.out.println("Account and password does not match.");
}
} else {
System.out.println("Account Name does not exist!");
}
in.close();
}
private void deposit(int accountNumber){
double amount = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter amount to deposit: ");
String amt = in.nextLine();
try {
amount = Double.parseDouble(amt);
} catch (Exception e){
System.out.println("Invalid input.");
}
double bal = balance.get(accountNumber);
bal = bal + amount;
balance.set(accountNumber,bal);
in.close();
}
private void withdraw(int accountNumber){
double amount = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter amount to withdraw: ");
String amt = in.nextLine();
try{
amount = Double.parseDouble(amt);
} catch (Exception e) {
System.out.println("You must input a number.");
}
double bal = balance.get(accountNumber);
if(amount > bal){
System.out.println("Insufficient funds.");
} else {
bal = bal - amount;
balance.set(accountNumber,bal);
}
in.close();
}
private void balance(int accountNumber){
double bal = balance.get(accountNumber);
System.out.println("Balance is " + bal + ".");
}
private int accountSearch(String s){
for(int i=0;i if(s.equalsIgnoreCase(name.get(i))){
return i;
}
}
return -1;
}
private void loadFile(){
Scanner inFile = null;
try {
inFile = new Scanner(file);
String acct = "";
String pass = "";
double bal = 0;
while (inFile.hasNextLine()){ //loops through the file as long as there is a next line
String line = inFile.nextLine(); //reads the next lineof the file
acct = line.substring(0,line.indexOf("|")); //extracts all characters to the left of the |
pass =
line.substring(line.indexOf("|")+1,line.indexOf("|",line.indexOf("|")+1));
//extracts all chars between the two | symbols
bal =
Double.parseDouble(line.substring(line.lastIndexOf("|")+1,line.length()));
//extraces all chars from the second | to the end of the line thenparses it
name.add(acct); //add to vector of names
password.add(pass); //add to vector of passwords
balance.add(bal); //add to vector of balances
}
inFile.close();
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
private void writeFile(){
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(file,false); //true to append,false to overwrite
dos = new DataOutputStream(fos);
for(int i=0;i dos.writeBytes(name.get(i) + "|" + password.get(i) +
"|" + balance.get(i) + "\n");
// write data to file in this format: name|password|balance
}
fos.close();
dos.close();
} catch (Exception e) {
System.out.println("Could not write file.");
}
}
}
import java.io.*;
public class ATM {
Vector
Vector
Vector
File file = new File("data.txt");
public ATM(){
balance = new Vector
name = new Vector
password = new Vector
//init();
}
public void init(){
int option = 0;
loadFile();
Scanner in = new Scanner(System.in);
do {
System.out.println("[1] Create new Account");
System.out.println("[2] Access Existing Account");
System.out.println("[3] Exit");
System.out.print("> ");
String input = in.nextLine();
try {
option = Integer.parseInt(input);
} catch (Exception e){
option = 0;
}
if(option > 3 || option < 1){
System.out.println("Invalid input.");
continue;
}
if(option == 1){
create();
}
if(option == 2){
open();
}
} while (option != 3);
in.close();
writeFile();
}
private void create(){
Scanner in = new Scanner(System.in);
System.out.print("Enter Account Name: ");
String actname = in.nextLine();
if(accountSearch(actname)>=0){
System.out.println("Account Already Exists.");
} else {
name.add(actname);
System.out.print("Enter Password: ");
password.add(in.nextLine());
balance.add(0.0);
System.out.println("Account " + name.lastElement() + " created!");
}
in.close();
}
private void open(){
Scanner in = new Scanner(System.in);
System.out.print("Enter Account Name: ");
int accountNumber = accountSearch(in.nextLine());
if(accountNumber >= 0){
System.out.print("Enter Password: ");
if(password.get(accountNumber).equals(in.nextLine())){
int option = 0;
double amount = 0;
do {
System.out.println("[1] Deposit Funds");
System.out.println("[2] Withdraw Funds");
System.out.println("[3] Balance Inquiry");
System.out.println("[4] Exit");
System.out.print("> ");
option = in.nextInt();
if(option > 4 || option < 1){
System.out.println("Invalid input.");
continue;
}
if(option == 1){
deposit(accountNumber);
}
if(option == 2){
withdraw(accountNumber);
}
if(option == 3){
balance(accountNumber);
}
} while (option != 4);
} else {
System.out.println("Account and password does not match.");
}
} else {
System.out.println("Account Name does not exist!");
}
in.close();
}
private void deposit(int accountNumber){
double amount = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter amount to deposit: ");
String amt = in.nextLine();
try {
amount = Double.parseDouble(amt);
} catch (Exception e){
System.out.println("Invalid input.");
}
double bal = balance.get(accountNumber);
bal = bal + amount;
balance.set(accountNumber,bal);
in.close();
}
private void withdraw(int accountNumber){
double amount = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter amount to withdraw: ");
String amt = in.nextLine();
try{
amount = Double.parseDouble(amt);
} catch (Exception e) {
System.out.println("You must input a number.");
}
double bal = balance.get(accountNumber);
if(amount > bal){
System.out.println("Insufficient funds.");
} else {
bal = bal - amount;
balance.set(accountNumber,bal);
}
in.close();
}
private void balance(int accountNumber){
double bal = balance.get(accountNumber);
System.out.println("Balance is " + bal + ".");
}
private int accountSearch(String s){
for(int i=0;i
return i;
}
}
return -1;
}
private void loadFile(){
Scanner inFile = null;
try {
inFile = new Scanner(file);
String acct = "";
String pass = "";
double bal = 0;
while (inFile.hasNextLine()){ //loops through the file as long as there is a next line
String line = inFile.nextLine(); //reads the next lineof the file
acct = line.substring(0,line.indexOf("|")); //extracts all characters to the left of the |
pass =
line.substring(line.indexOf("|")+1,line.indexOf("|",line.indexOf("|")+1));
//extracts all chars between the two | symbols
bal =
Double.parseDouble(line.substring(line.lastIndexOf("|")+1,line.length()));
//extraces all chars from the second | to the end of the line thenparses it
name.add(acct); //add to vector of names
password.add(pass); //add to vector of passwords
balance.add(bal); //add to vector of balances
}
inFile.close();
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
private void writeFile(){
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream(file,false); //true to append,false to overwrite
dos = new DataOutputStream(fos);
for(int i=0;i
"|" + balance.get(i) + "\n");
// write data to file in this format: name|password|balance
}
fos.close();
dos.close();
} catch (Exception e) {
System.out.println("Could not write file.");
}
}
}
CS Practest (Review + Reminders!)
Thursday, November 26, 2009
Er, yeah.
I got an email from Sir Paolo.
Hi guys! Sorry but i wont be able to be there tomorrow for the
practical test so here are some more pointers and answers to questions
you might ask:
1. BlueJ in the new lab is located in C:\CS3 and so is Java
(C:\Sun\SDK\jdk\bin\java)
2. Save your file inside your sections folder inside the BlueJ folder.
Kung wala pang section folder, create a new one.
3. The test is open notes so print all the codes you need
4. Coverage is inheritance and abstract classes ONLY. So be sure you
know how to use super!
5. If you're using arrays or vectors during the test, you're probably
doing something wrong.
6. The test is long but managable. Don't be stuck in one particular
part. If you can't make one of the classes/methods work, move on to
the next one muna.
GOODLUCK!!! See you on Tuesday/Wednesday...
- Sir Paolo :D
I got an email from Sir Paolo.
Hi guys! Sorry but i wont be able to be there tomorrow for the
practical test so here are some more pointers and answers to questions
you might ask:
1. BlueJ in the new lab is located in C:\CS3 and so is Java
(C:\Sun\SDK\jdk\bin\java)
2. Save your file inside your sections folder inside the BlueJ folder.
Kung wala pang section folder, create a new one.
3. The test is open notes so print all the codes you need
4. Coverage is inheritance and abstract classes ONLY. So be sure you
know how to use super!
5. If you're using arrays or vectors during the test, you're probably
doing something wrong.
6. The test is long but managable. Don't be stuck in one particular
part. If you can't make one of the classes/methods work, move on to
the next one muna.
GOODLUCK!!! See you on Tuesday/Wednesday...
- Sir Paolo :D
public abstract class Polygon {
public abstract double perimeter();
public abstract double area();
}
import java.util.*;
public class Triangle extends Polygon {
double side1;
double side2;
double side3;
public Triangle(double s1, double s2, double s3){
side1 = s1;
side2 = s2;
side3 = s3;
}
public double perimeter(){
return side1 + side2 + side3;
}
public double area(){
double s = perimeter() / 2;
return Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
}
}
import java.util.*;
public class Equilateral extends Triangle {
public Equilateral(double side){
super(side,side,side);
}
public double perimeter(){
return side3*3;
}
public double area(){
return side1 * Math.sqrt(3)/4;
}
}
public class Isosceles extends Triangle {
public Isosceles(double s1,double s2){
super(s1,s1,s2);
}
public double perimeter(){
return side1*2 + side3;
}
}
public class Scalene extends Triangle{
//walang laman
}
public abstract class RegularPolygon extends Polygon {
int numberOfSides;
double length;
public RegularPolygon(int n, double l){
length = l;
numberOfSides = n;
}
public double perimeter(){
return length * numberOfSides;
}
public abstract double area();
}
CS Homework + Scanner + Buffer
Monday, November 23, 2009
Supposedly, you're to ask the user for the Array size and the Elements.
And output the following:
1 - Minimum Value
2 - Maximum Value
3 - Mean / Average Value
For bonus points:
4 - Median
5 - Mode
SCANNER
BUFFER
And output the following:
1 - Minimum Value
2 - Maximum Value
3 - Mean / Average Value
For bonus points:
4 - Median
5 - Mode
SCANNER
import java.util.Scanner;
public class InputByScanner {
public static void main(String[] args) {
String name;
int age;
Scanner in = new Scanner(System.in);
System.out.print("Input Name: ");
name = in.nextLine();
System.out.print("Input Age: ");
age =in.nextInt();
in.close();
// Prints name and age to the console
System.out.println("Name :"+name);
System.out.println("Age :"+age);
}
}
BUFFER
import java.io.*;
public class InputByBufferReader {
public static void main(String args[]) throws IOException {
String s = "";
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
do{
System.out.print("Input: ");
s = in.readLine();
System.out.println("You typed: " + s);
}while(!s.equalsIgnoreCase("exit"));
in.close();
}
}
Farmer/Plant Exercise
Saturday, October 24, 2009
Emailed by Sir Paolo.
:">
:">
public class Plant{
int height;
int value; //Selling price. Increases as plant grows
String type; //Type of Plant (ex. Apple, Banana, Carrot)
public Plant(){
type = "Generic Plant";
height = 0;
}
public Plant(int h){
height = h;
type = "Generic Plant";
}
public void grow(){
height = height + 10;
value = value + 100;
}
public void grow(int h){
height = height + h;
value = value + 10 * h;
}
public int getHeight(){
return height;
}
public int getValue(){
return value;
}
public String getType(){
return type;
}
}
public class FruitPlant extends Plant{
int numberOfFruit;
int fruitValue;
public FruitPlant(){
super();
type = "Generic Fruit Plant";
}
public void grow(){
super.grow();
numberOfFruit++;
}
public void grow(int i){
super.grow(i);
bearFruit();
}
public void bearFruit(){
numberOfFruit++;
}
public int harvestFruit(){
if(numberOfFruit>0){
numberOfFruit--;
return fruitValue;
} else {
return 0;
}
}
public int numberOfFruit(){
return numberOfFruit;
}
}
Plant Java program
Thursday, October 22, 2009
public class Plant{
int height;
int value;
String type;
public Plant(){
height = 0;
type = "Generic Plant";
}
public Plant(int h){
height = h;
type = "Generic Plant";
}
public void Grow(){
height = height + 10;
value = value + 100;
}
public void Grow(int h){
height = height + h;
value = value + 100 * h;
}
public int getValue(){
return value;
}
public int getHeight(){
return height;
}
public String getType(){
return type;
}
}
para sa mga nakalimot o di nkapagsave sa mga USB (tulad ko kaya kailangan ko tuloy isipin kung anu nga ung program)
int height;
int value;
String type;
public Plant(){
height = 0;
type = "Generic Plant";
}
public Plant(int h){
height = h;
type = "Generic Plant";
}
public void Grow(){
height = height + 10;
value = value + 100;
}
public void Grow(int h){
height = height + h;
value = value + 100 * h;
}
public int getValue(){
return value;
}
public int getHeight(){
return height;
}
public String getType(){
return type;
}
}
para sa mga nakalimot o di nkapagsave sa mga USB (tulad ko kaya kailangan ko tuloy isipin kung anu nga ung program)
CD + Player
Thursday, September 17, 2009
public class CD {
//attributes
String name;
String[] tracks;
public CD(String s){
name = s;
}
public CD(String s, String[] tracklist){
tracks = tracklist;
name = s;
}
public void setTracks(String[] tracklist){
tracks = tracklist;
}
public String play(int tracknum){
if(tracks.length > 0){
return tracks[tracknum];
} else {
return "CD has no tracks";
}
}
public int getTracks(){
return tracks.length;
}
}
public class CDPlayer {
//attributes
int track_num = 0;
String status = "stop";
CD CDin;
public void play(){
if(CDin != null){
status = "play";
System.out.println("Now playing:" + CDin.play(track_num));
} else {
System.out.println("There is no CD in the Player!");
}
}
public void stop(){
status = "stop";
}
public void pause(){
if(CDin != null){
status = "pause";
} else {
System.out.println("There is no CD in the Player!");
}
}
public void load(CD newcd){
CDin = newcd;
}
public void forward(){
if(CDin != null){
track_num++;
if(track_num > CDin.getTracks()-1){
track_num = 0;
}
if(status == "play"){
System.out.println("Now playing:" + CDin.play(track_num));
}
} else {
System.out.println("There is no CD in the Player!");
}
}
public void rewind(){
if(CDin != null){
track_num--;
if(track_num < 1){
track_num = CDin.getTracks()-1;
}
if(status == "play"){
System.out.println("Now playing:" + CDin.play(track_num));
}
} else {
System.out.println("There is no CD in the Player!");
}
}
}
//attributes
String name;
String[] tracks;
public CD(String s){
name = s;
}
public CD(String s, String[] tracklist){
tracks = tracklist;
name = s;
}
public void setTracks(String[] tracklist){
tracks = tracklist;
}
public String play(int tracknum){
if(tracks.length > 0){
return tracks[tracknum];
} else {
return "CD has no tracks";
}
}
public int getTracks(){
return tracks.length;
}
}
public class CDPlayer {
//attributes
int track_num = 0;
String status = "stop";
CD CDin;
public void play(){
if(CDin != null){
status = "play";
System.out.println("Now playing:" + CDin.play(track_num));
} else {
System.out.println("There is no CD in the Player!");
}
}
public void stop(){
status = "stop";
}
public void pause(){
if(CDin != null){
status = "pause";
} else {
System.out.println("There is no CD in the Player!");
}
}
public void load(CD newcd){
CDin = newcd;
}
public void forward(){
if(CDin != null){
track_num++;
if(track_num > CDin.getTracks()-1){
track_num = 0;
}
if(status == "play"){
System.out.println("Now playing:" + CDin.play(track_num));
}
} else {
System.out.println("There is no CD in the Player!");
}
}
public void rewind(){
if(CDin != null){
track_num--;
if(track_num < 1){
track_num = CDin.getTracks()-1;
}
if(status == "play"){
System.out.println("Now playing:" + CDin.play(track_num));
}
} else {
System.out.println("There is no CD in the Player!");
}
}
}
Arrays
Tuesday, September 15, 2009
Kelangan ko na magconsult, I swear. XD
public class Arrays
{
int[] arrayOfTenIntegers = new int[10];
Point[] arrayOfTenPoints = new Point[5];
int[] xc = {12,321,54,12,53};
int[] yc = {32,38,21,31,123};
public void initInts(){
for(int x=0;x<10;x++){
arrayOfTenIntegers[x] = x+1;
}
}
public void initPoints(){
for(int x=0;x<5;x++){
Point p = new Point(xc[x],yc[x]);
arrayOfTenPoints[x] = p;
}
}
public double getTotalDistance(){
double distance = 0;
for(int x=0;x<4;x++){
distance = distance +
arrayOfTenPoints[x].distanceTo(arrayOfTenPoints[x+1]);
}
return distance;
}
}
Circle Code
Thursday, September 10, 2009
import java.util.*;
public class Circle {
//Attributes
Point center;
double radius;
public Circle(){
center = new Point();
radius = 1;
}
public Circle(double x, double y, double r){
center = new Point(x,y);
radius = r;
}
public Circle(Point p, double r){
radius = r;
center = p;
}
public Circle(LineSegment diameter){
center = diameter.midpoint();
radius = diameter.length()/2;
}
public String getEquation(){
String s = "(x -" + center.getX() + ")^2";
s = s + " + (y -" + center.getY() + ")^2";
s = s + " = " + radius* radius;
return s;
}
}
public class Circle {
//Attributes
Point center;
double radius;
public Circle(){
center = new Point();
radius = 1;
}
public Circle(double x, double y, double r){
center = new Point(x,y);
radius = r;
}
public Circle(Point p, double r){
radius = r;
center = p;
}
public Circle(LineSegment diameter){
center = diameter.midpoint();
radius = diameter.length()/2;
}
public String getEquation(){
String s = "(x -" + center.getX() + ")^2";
s = s + " + (y -" + center.getY() + ")^2";
s = s + " = " + radius* radius;
return s;
}
}
CS Point and Line Segments Program
Thursday, September 03, 2009
In-email ni Sir Paolo, kasi hindi in-email ni Domz. :>
import java.util.*;
public class Point {
//ATTRIBUTES
double x;
double y;
public Point(){
x = 0;
y = 0;
}
public Point(double a, double b){
x = a;
y = b;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void move(double a,double b){
x = a;
y = b;
}
public double distanceTo(Point p){
double distance =
Math.pow(x - p.getX(),2) +
Math.pow(y - p.getY(),2);
return Math.sqrt(distance);
}
public double distanceTo(double a,double b){
double distance =
Math.pow(x - a,2) +
Math.pow(y - b,2);
return Math.sqrt(distance);
}
}
public class LineSegment {
//ATTRIBUTES
Point endpoint1;
Point endpoint2;
public LineSegment(Point a, Point b){
endpoint1 = a;
endpoint2 = b;
}
public double length(){
return endpoint2.distanceTo(endpoint1);
}
public Point midpoint(){
double x =
(endpoint1.getX() + endpoint2.getX())/2;
double y =
(endpoint1.getY() + endpoint2.getY())/2;
Point midpoint = new Point(x,y);
return midpoint;
}
public double slope(){
double rise =
endpoint1.getY() - endpoint2.getY();
double run =
endpoint1.getX() - endpoint2.getX();
return rise/run;
}
public String getLine(){
String s =
"Y = ";
s = s + slope() + "(X) - ";
s =s + (slope()*endpoint1.getX() + endpoint1.getY());
return s;
}
}
CS Car Program
Tuesday, August 25, 2009
The java program Sir Paolo typed up during our CS period today. I was trying so hard not to use "kanina".
I still don't understand why he also sent Chester a copy. :-j
I still don't understand why he also sent Chester a copy. :-j
import java.util.*;
public class Car2 {
int position_x;
int position_y;
String direction = "up";
public void moveForward(int amount) {
if(direction == "up"){
position_y = position_y + amount;
} else if(direction == "right") {
position_x = position_x + amount;
} else if(direction == "down") {
position_y = position_y - amount;
} else if(direction == "left") {
position_x = position_x - amount;
}
}
public void moveBackward(int amount) {
if(direction == "up"){
position_y = position_y - amount;
} else if(direction == "right") {
position_x = position_x - amount;
} else if(direction == "down") {
position_y = position_y + amount;
} else if(direction == "left") {
position_x = position_x + amount;
}
}
public void turnRight(){
if(direction == "up"){
direction = "right";
} else if(direction == "right") {
direction = "down";
} else if(direction == "down") {
direction = "left";
} else if(direction == "left") {
direction = "up";
}
}
public void turnLeft(){
if(direction == "up"){
direction = "left";
} else if(direction == "right") {
direction = "up";
} else if(direction == "down") {
direction = "right";
} else if(direction == "left") {
direction = "down";
}
}
public double getDisplacement(){
double displacement = (position_x * position_x) + (position_y * position_y);
return Math.sqrt(displacement);
}
}


