Monday, May 11, 2009

Calculator in Java Console Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Calculator {


public static int validate(String input){//validate the user input value
try
{
int output = Integer.parseInt (input);//convert the string to integer
return output;
}
catch (Exception e){//if input value is not integer,return -1
System.out.println(e.getMessage());//print the exception message
return -1;
}
} //end validate function

/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub


BufferedReader br = new BufferedReader (new InputStreamReader (System.in));//read the input from console

while(true){

System.out.print ( "\nEnter the first number: " );

String input1 = br.readLine();//get input1

System.out.print ( "\nEnter the second number: " );

String input2 = br.readLine();//get input2

int num1 = validate(input1);//call the validate function and pass input1

int num2 = validate(input2);//call the validate function and pass input2

if(num1 == -1 || num2 == -1){//check the condition
System.out.println("You enter correct interger value...");
}
else{

System.out.println("\n1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Exit");

System.out.print( "Enter your choice : ");

int option = Integer.parseInt(br.readLine());//get the choice of the user

switch(option){//switch to the value of choice

case 1:

int addAnswer = num1 + num2;//add the user input value

System.out.println(num1+" + "+num2+" = "+addAnswer);

break;

case 2:

int subAnswer = num1 - num2;//Subtract the user input value

System.out.println(num1+" - "+num2+" = "+subAnswer);

break;

case 3:

int mulAnswer = num1 * num2;//Multiply the user input value

System.out.println(num1+" * "+num2+" = "+mulAnswer);

break;

case 4:


if(num2 != 0){

double divAnswer = (double)num1 / (double)num2;//Divide the user input value and assign to double

System.out.println(num1+" / "+num2+" = "+divAnswer);

}else{

System.out.println ("Division by zero is not allowed!");
}

break;

case 5:

System.exit(0);//exit the program

default:

System.out.println("Enter your correct choice...");

}//end switch statement
}

}//end while loop

}//end main method
}

Read more...

Tuesday, April 28, 2009

Housing Price Simulation using Java Swing

School
? Catchment area of school defines the area of houses influenced by the presence of the school.
? Catchment area for schools is 3km.
? The degree to which a school is considered good or bad is its influence level.
? Influence level is randomly assigned to each school in neighbourhood.
? Influence level: -10 being the worst (negatively influenced), 10 being the best (positively influenced).
? Houses within the 3km proximity radius will show an increase in price of 15%
? However “bad” schools will have no negative effect on house price.

Industrial Estates
? Catchment area of industrial estates defines the area of houses influence by its presence.
? Catchment area for industrial estates is 0.5km
? Industrial estate agents will group together to from an “industrial estate.”
? Industrial estates will have an influence level of -6.

Topography
? Topography defined as scenic areas, countryside, lakes, parks.
? Catchment area of topography defines the area of houses influence by its presence.
? Catchment area for topography 0.5km.
? Influence level for topography range from +5 to +10


Pubs
? Catchment area for pubs ranges from 0.5km to 4km
? Houses within 0.5km of the pub will negatively influence house prices by 8%
? Houses within 0.5km of pubs will carry the negative influence level of
? Houses outside 0.5km of the pub will positively influence house prices by 3%
? Houses outside 0.5km of pubs will carry the positive influence level of
? Influence level for topography range from +5 to +10

Town Centre
? Catchment area for town centre is 1.5km
? Houses prices within this catchment area will be positively influenced by 20%


Interest rates
? When interest rates increase, demand for housing decreases, therefore decrease in price.
? Interest rate ranges from 0 to 15.
? Demand for housing will be measured as a percentage change of the interest rate.
? E.g. if interest rate increases from 4.0 to 4.6 (change being +0.6) then demand decreases by 15% as does house price.

Policing Level
? If level of policing is 0-30% reduce all agents influence level by 5.
? If level of policing is 30-60% reduce all agents influence level by 3.
? If level of policing is 60-100% reduce all agents influence level by 1.




Inputs
Before the simulation is run the user will be able to set up the neighbourhood.

Interest rates
? Interest rates will range from 0 to 15.
? User will have the option to set default value for simulation (5)

Population
? Users will also be able to set the population density for the neighbourhood.
? Population density will range from 0 to 100%
? And will directly effect demand e.g. when population is at 100%, demand is at its highest (therefore price will be equally as high).
? User will have the option to set default value for simulation (75%)
?
Level of policing

General Inputs
? Users will be able to set default values for everything to allow the system run a controlled simulation.
? Users can set the catchment area and influence level for each amenity
? All houses start off with a default price of £100,000


Outputs
The outputs will be shown on a GUI that will help analyse the simulation as a whole.
Each agent will have its own colour, for example houses will be in blue, topography in green and so on.
To represent the difference in house price within the actual simulation, differeing house prices will be represented by different shades of blue. For example houses prices between 0 and 50,000 will show as a light blue, 50,000 to 100,000 a darker shade, 100,000 to 150,000 an even darker shade, until it reaches its maximum category 300,000+.


? Display all input values including interest rate, population
? The number of houses in the simulation
? The number of houses in each price category
? The average house price will be calculated
? The highest and lowest house price will be displayed
? Display the number of each amenity-school pubs topography etc


Source code:
------------

HouseMarketGUI.java
-------------------

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Graphics;
import java.awt.Color;
public class HouseMarketGUI extends JFrame implements ActionListener{

int population ;
int interestRate ;
int policingLevel ;

double topographyCatchment;
double industrialsCatchment;
double towncentreCatchment;
double pubsCatchment;
double schoolCatchment;

static HouseMarketGUI gui;
//Page1 GUI Variables
private JLabel p1labelt;
private JLabel p1labeltSub;
private JFrame p1frame;
private JLabel p1popLable;
private JLabel p1intLable;
private JLabel p1poliLable;
private JTextField p1popValue;
private JTextField p1intValue;
private JTextField p1poliValue;

private JButton p1button;
//end
// Page2 GUI Variables
private JLabel p2labelt;
private JLabel p2labeltSub;
private JFrame p2frame;
private JLabel p2nameLable;
private JLabel p2numberLable;
private JLabel p2salaryLable;
private JLabel p2pubLable;
private JLabel p2schoolLable;

private JLabel p2topdefLable;
private JLabel p2inddefLable;
private JLabel p2towndefLable;
private JLabel p2pubdefLable;
private JLabel p2schooldefLable;

private JTextField p2numberValue;
private JTextField p2namevalue;
private JTextField p2salaryValue;
private JTextField p2pubValue;
private JTextField p2schoolValue;

private JButton p2topdefValue;
private JButton p2inddefValue;
private JButton p2towndefValue;
private JButton p2pubdefValue;
private JButton p2schooldefValue;


private JButton p2button;
private JButton p2button2;
// end
// Page3 GUI Variables
private JLabel p3labelt;
private JLabel p3labeltSub;
private JLabel p3labeltSubs;
private JLabel p3labeltrSub;
private JLabel p3labeltrSubs;

static JFrame p3frame;

private JLabel p3housesLable;
private JLabel p3topLable;
private JLabel p3indLable;
private JLabel p3townLable;
private JLabel p3pubLable;
private JLabel p3schoolLable;


private JLabel p3to100Lable;
private JLabel p3to250Lable;
private JLabel p3to500Lable;
private JLabel p3to1000Lable;
private JLabel p3to1001Lable;
private JLabel p3AvgPriceLable;

public static JTextField p3housesValue;
public static JTextField p3topValue;
public static JTextField p3indValue;
public static JTextField p3townValue;
public static JTextField p3pubValue;
public static JTextField p3schoolValue;


private JTextField p3to100Value;
private JTextField p3to250Value;
private JTextField p3to500Value;
private JTextField p3to1000Value;
private JTextField p3to1001Value;
private JTextField p3AvgPriceValue;
private JTextField p3XYearSimValue;


private JLabel p3popLable;
private JLabel p3intLable;
private JLabel p3poliLable;
private JTextField p3popValue;
private JTextField p3intValue;
private JTextField p3poliValue;


private JButton p3button;
private JButton p3button2;
private JButton p3button3;
//end


HousePriceFactors housePriceFactor;




public HouseMarketGUI(){

housePriceFactor = new HousePriceFactors();

// size = new Dimension(0, 0);
// stats = new FieldStats();
// JPanel cp = new JPanel(new GridLayout(1, 1));
// JPanel cp1 = new JPanel();
//Page1 Create Object
p1frame= new JFrame(" Housing Market Simulation ");
p1frame.getContentPane().setLayout(null);

p1labelt = new JLabel("Housing Market Simulation");
p1labelt.setFont(new Font("Serif", Font.BOLD, 20));
p1labelt.setBounds(150,0,350,70);

p1labeltSub = new JLabel("Setup Environment");
p1labeltSub.setFont(new Font("Serif", Font.BOLD, 18));
p1labeltSub.setBounds(50,40,350,70);

p1popLable = new JLabel("Population(0-100)%");
p1popValue = new JTextField(35);
p1popValue.setText("75");
p1intLable = new JLabel("Interest Rate(0-15)");
p1intValue = new JTextField(35);
p1intValue.setText("5");

p1poliLable = new JLabel("Policing Level(0-100)%");
p1poliValue = new JTextField(35);
p1poliValue.setText("50");

p1button = new JButton("NEXT");
//end

// Page2 Create Object
p2frame= new JFrame(" Housing Market Simulation ");
p2frame.getContentPane().setLayout(null);

p2labelt = new JLabel("Housing Market Simulation");
p2labelt.setFont(new Font("Serif", Font.BOLD, 20));
p2labelt.setBounds(150,0,350,70);

p2labeltSub = new JLabel("Setup Neighborhood");
p2labeltSub.setFont(new Font("Serif", Font.BOLD, 18));
p2labeltSub.setBounds(50,40,350,70);

p2nameLable = new JLabel("Topography CatchmentArea(km)");
p2namevalue = new JTextField(35);

p2numberLable = new JLabel("Industrial CatchmentArea(km)");
p2numberValue = new JTextField(35);

p2salaryLable = new JLabel("Town Centre CatchmentArea(km)");
p2salaryValue = new JTextField(35);

p2pubLable = new JLabel("Pubs & Bars CatchmentArea(km)");
p2pubValue = new JTextField(35);

p2schoolLable = new JLabel("Schools CatchmentArea(km)");
p2schoolValue = new JTextField(35);

//default
p2topdefLable = new JLabel("Default(0.5km)");
p2topdefValue = new JButton(" X ");

p2inddefLable = new JLabel("Default(0.5km)");
p2inddefValue = new JButton(" X ");

p2towndefLable = new JLabel("Default(1.5km)");
p2towndefValue = new JButton(" X ");

p2pubdefLable = new JLabel("Default(0.5km)");
p2pubdefValue = new JButton(" X ");

p2schooldefLable = new JLabel("Default(3.0km)");
p2schooldefValue = new JButton(" X ");

p2button = new JButton("BACK");
p2button2 = new JButton("Simulate");
//end

// Page3 Create Object
p3frame= new JFrame(" Housing Market Simulation ");
//p3frame.getContentPane().setLayout(null);

p3labelt = new JLabel("Housing Market Simulation");
p3labelt.setFont(new Font("Serif", Font.BOLD, 20));
p3labelt.setBounds(150,0,350,70);

p3labeltSub = new JLabel("Statistics");
p3labeltSub.setFont(new Font("Serif", Font.BOLD, 19));
p3labeltSub.setBounds(50,40,350,60);

p3labeltSubs = new JLabel("Legend");
p3labeltSubs.setFont(new Font("Serif", Font.BOLD, 14));
p3labeltSubs.setBounds(50,80,250,30);

p3labeltrSub = new JLabel("House Prices");
p3labeltrSub.setFont(new Font("Serif", Font.BOLD, 19));
p3labeltrSub.setBounds(600,40,250,30);

p3labeltrSubs = new JLabel("$(000)");
p3labeltrSubs.setFont(new Font("Serif", Font.BOLD, 14));
p3labeltrSubs.setBounds(600,80,250,30);



p3housesLable = new JLabel("Houses");
p3housesValue = new JTextField(35);

p3topLable = new JLabel("Topography");
p3topValue = new JTextField(35);

p3indLable = new JLabel("Industrial");
p3indValue = new JTextField(35);

p3townLable = new JLabel("Town Centre");
p3townValue = new JTextField(35);

p3pubLable = new JLabel("Pubs");
p3pubValue = new JTextField(35);

p3schoolLable = new JLabel("School");
p3schoolValue = new JTextField(35);

//default
p3to100Lable = new JLabel("0-100");
p3to100Value = new JTextField(35);

p3to250Lable = new JLabel("100-250");
p3to250Value = new JTextField(35);

p3to500Lable = new JLabel("250-500");
p3to500Value = new JTextField(35);

p3to1000Lable = new JLabel("500-1,000");
p3to1000Value = new JTextField(35);

p3to1001Lable = new JLabel("1,000 +");
p3to1001Value = new JTextField(35);

p3AvgPriceLable = new JLabel("Average price");
p3AvgPriceValue = new JTextField(35);

p3XYearSimValue = new JTextField(20);

p3popLable = new JLabel("Population(0-100)%");
p3popValue = new JTextField(35);
p3intLable = new JLabel("Interest Rate(0-15)");
p3intValue = new JTextField(35);
p3poliLable = new JLabel("Policing Level(0-100)%");
p3poliValue = new JTextField(35);


p3button = new JButton("Simulate 1 Year");
p3button2 = new JButton("Simulate X Year");
p3button3 = new JButton("Close");
//end

//Page1 Position
p1popLable.setBounds(50,100,150,70);
p1intLable.setBounds(50,150,150,70);

p1popValue.setBounds(220,120,50,30);
p1intValue.setBounds(220,170,50,30);

p1poliLable.setBounds(50,200,150,70);
p1poliValue.setBounds(220,220,50,30);

p1button.setBounds(370,330,80,27);
//end
//Page2 Position
p2nameLable.setBounds(50,100,220,70);
p2namevalue.setBounds(250,120,50,30);

p2numberLable.setBounds(50,150,220,70);
p2numberValue.setBounds(250,170,50,30);

p2salaryLable.setBounds(50,200,220,70);
p2salaryValue.setBounds(250,220,50,30);

p2pubLable.setBounds(50,250,220,70);
p2pubValue.setBounds(250,270,50,30);

p2schoolLable.setBounds(50,300,220,70);
p2schoolValue.setBounds(250,320,50,30);

//default
p2topdefLable.setBounds(350,100,150,70);
p2topdefValue.setBounds(450,120,50,30);

p2inddefLable.setBounds(350,150,150,70);
p2inddefValue.setBounds(450,170,50,30);

p2towndefLable.setBounds(350,200,150,70);
p2towndefValue.setBounds(450,220,50,30);

p2pubdefLable.setBounds(350,250,150,70);
p2pubdefValue.setBounds(450,270,50,30);

p2schooldefLable.setBounds(350,300,150,70);
p2schooldefValue.setBounds(450,320,50,30);

p2button.setBounds(30,400,80,27);
p2button2.setBounds(370,400,100,27);
//end
//Page3 Position
p3housesLable.setBounds(50,100,80,70);
p3housesValue.setBounds(140,120,50,30);

p3topLable.setBounds(50,150,80,70);
p3topValue.setBounds(140,170,50,30);

p3indLable.setBounds(50,200,80,70);
p3indValue.setBounds(140,220,50,30);

p3townLable.setBounds(50,250,80,70);
p3townValue.setBounds(140,270,50,30);

p3pubLable.setBounds(50,300,80,70);
p3pubValue.setBounds(140,320,50,30);

p3schoolLable.setBounds(50,350,80,70);
p3schoolValue.setBounds(140,370,50,30);

//default
p3to100Lable.setBounds(600,100,150,70);
p3to100Value.setBounds(660,120,90,30);
p3to100Value.setEditable(false);

p3to250Lable.setBounds(600,150,150,70);
p3to250Value.setBounds(660,170,90,30);
p3to250Value.setEditable(false);

p3to500Lable.setBounds(600,200,150,70);
p3to500Value.setBounds(660,220,90,30);
p3to500Value.setEditable(false);

p3to1000Lable.setBounds(600,250,150,70);
p3to1000Value.setBounds(660,270,90,30);
p3to1000Value.setEditable(false);

p3to1001Lable.setBounds(600,300,150,70);
p3to1001Value.setBounds(660,320,90,30);
p3to1001Value.setEditable(false);

p3AvgPriceLable.setBounds(560,350,170,70);
p3AvgPriceValue.setBounds(650,370,90,30);
p3AvgPriceValue.setEditable(false);

p3XYearSimValue.setBounds(460,520,30,30);

p3popLable.setBounds(50,450,150,70);
p3popValue.setBounds(220,470,50,30);

p3intLable.setBounds(50,500,150,70);
p3intValue.setBounds(220,520,50,30);

p3poliLable.setBounds(50,550,150,70);
p3poliValue.setBounds(220,570,50,30);

//button.setBounds(80,450,150,27);
p3button.setBounds(520,480,140,27);
p3button2.setBounds(520,520,140,27);
p3button3.setBounds(520,560,140,27);
//end

//page1 add contentPanel
p1frame.getContentPane().add(p1labelt);
p1frame.getContentPane().add(p1labeltSub);

p1frame.getContentPane().add(p1popLable);
p1frame.getContentPane().add(p1popValue);
p1frame.getContentPane().add(p1intLable);
p1frame.getContentPane().add(p1intValue);

p1frame.getContentPane().add(p1poliLable);
p1frame.getContentPane().add(p1poliValue);

p1frame.getContentPane().add(p1button);
//end

//page2 add contentPanel
p2frame.getContentPane().add(p2labelt);
p2frame.getContentPane().add(p2labeltSub);

p2frame.getContentPane().add(p2nameLable);
p2frame.getContentPane().add(p2namevalue);

p2frame.getContentPane().add(p2numberLable);
p2frame.getContentPane().add(p2numberValue);

p2frame.getContentPane().add(p2salaryLable);
p2frame.getContentPane().add(p2salaryValue);

p2frame.getContentPane().add(p2pubLable);
p2frame.getContentPane().add(p2pubValue);

p2frame.getContentPane().add(p2schoolLable);
p2frame.getContentPane().add(p2schoolValue);

//default
p2frame.getContentPane().add(p2topdefLable);
p2frame.getContentPane().add(p2topdefValue);

p2frame.getContentPane().add(p2inddefLable);
p2frame.getContentPane().add(p2inddefValue);

p2frame.getContentPane().add(p2towndefLable);
p2frame.getContentPane().add(p2towndefValue);

p2frame.getContentPane().add(p2pubdefLable);
p2frame.getContentPane().add(p2pubdefValue);

p2frame.getContentPane().add(p2schooldefLable);
p2frame.getContentPane().add(p2schooldefValue);

p2frame.getContentPane().add(p2button);
p2frame.getContentPane().add(p2button2);
//end
//page3 add contentPanel
p3frame.getContentPane().add(p3labelt);
p3frame.getContentPane().add(p3labeltSub);
p3frame.getContentPane().add(p3labeltSubs);
p3frame.getContentPane().add(p3labeltrSub);
p3frame.getContentPane().add(p3labeltrSubs);

p3frame.getContentPane().add(p3housesLable);
p3frame.getContentPane().add(p3housesValue);

p3frame.getContentPane().add(p3topLable);
p3frame.getContentPane().add(p3topValue);

p3frame.getContentPane().add(p3indLable);
p3frame.getContentPane().add(p3indValue);

p3frame.getContentPane().add(p3townLable);
p3frame.getContentPane().add(p3townValue);

p3frame.getContentPane().add(p3pubLable);
p3frame.getContentPane().add(p3pubValue);

p3frame.getContentPane().add(p3schoolLable);
p3frame.getContentPane().add(p3schoolValue);

//default
p3frame.getContentPane().add(p3to100Lable);
p3frame.getContentPane().add(p3to100Value);

p3frame.getContentPane().add(p3to250Lable);
p3frame.getContentPane().add(p3to250Value);

p3frame.add(p3to500Lable);
p3frame.add(p3to500Value);

p3frame.getContentPane().add(p3to1000Lable);
p3frame.getContentPane().add(p3to1000Value);

p3frame.getContentPane().add(p3to1001Lable);
p3frame.getContentPane().add(p3to1001Value);

p3frame.getContentPane().add(p3AvgPriceLable);
p3frame.getContentPane().add(p3AvgPriceValue);
p3frame.getContentPane().add(p3XYearSimValue);

p3frame.getContentPane().add(p3popLable);
p3frame.getContentPane().add(p3popValue);
p3frame.getContentPane().add(p3intLable);
p3frame.getContentPane().add(p3intValue);
p3frame.getContentPane().add(p3poliLable);
p3frame.getContentPane().add(p3poliValue);





p3frame.getContentPane().add(p3button);
p3frame.getContentPane().add(p3button2);
p3frame.getContentPane().add(p3button3);
//end

//page1 actionListener
p1button.addActionListener(this);
p1frame.setSize(550,550);
p1frame.setVisible(true);
//end

//page2 actionListener
p2button.addActionListener(this);
p2button2.addActionListener(this);
p2topdefValue.addActionListener(this);
p2inddefValue.addActionListener(this);
p2towndefValue.addActionListener(this);
p2pubdefValue.addActionListener(this);
p2schooldefValue.addActionListener(this);

// X button actions implementation
// X button actions implementation
// X button actions implementation
// X button actions implementation
// X button actions implementation

p2frame.setSize(550,550);
p2frame.setVisible(false);
//end

Rectangles rects = new Rectangles();
p3frame.getContentPane().add(rects);

//page3 actionListener
p3button.addActionListener(this);
p3button2.addActionListener(this);
p3button3.addActionListener(this);
p3frame.setSize(780,650);
p3frame.setVisible(false);
//end



}

public void actionPerformed(ActionEvent event){

if(event.getSource() == p1button){
p1frame.setVisible(false);
p2frame.setVisible(true);
p3frame.setVisible(false);

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2namevalue.setEditable(false);
p2numberValue.setEditable(false);
p2salaryValue.setEditable(false);
p2pubValue.setEditable(false);
p2schoolValue.setEditable(false);

population = Integer.parseInt(p1popValue.getText());
interestRate = Integer.parseInt(p1intValue.getText());
policingLevel = Integer.parseInt(p1poliValue.getText());

housePriceFactor.setPopulation(population);
housePriceFactor.setInterestRate(interestRate);
housePriceFactor.setPolicingLevel(policingLevel);



}

if(event.getSource() == p2topdefValue){

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2namevalue.setEditable(true);

}

if(event.getSource() == p2inddefValue){

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2numberValue.setEditable(true);


}

if(event.getSource() == p2towndefValue){

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2salaryValue.setEditable(true);


}
if(event.getSource() == p2pubdefValue){

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2pubValue.setEditable(true);


}
if(event.getSource() == p2schooldefValue){

p2namevalue.setText("0.5");
p2numberValue.setText("0.5");
p2salaryValue.setText("1.5");
p2pubValue.setText("0.5");
p2schoolValue.setText("3.0");

p2schoolValue.setEditable(true);

}
if(event.getSource() == p2button){
p1frame.setVisible(true);
p2frame.setVisible(false);
p3frame.setVisible(false);

}




if(event.getSource() == p2button2){
p1frame.setVisible(false);
p2frame.setVisible(false);
p3frame.setVisible(true);

p3popValue.setText(population+"");
p3intValue.setText(interestRate+"");
p3poliValue.setText(policingLevel+"");
p3popValue.setEditable(false);
p3intValue.setEditable(false);
p3poliValue.setEditable(false);

topographyCatchment = Double.parseDouble(p2namevalue.getText());
industrialsCatchment = Double.parseDouble(p2numberValue.getText());
towncentreCatchment = Double.parseDouble(p2salaryValue.getText());
pubsCatchment = Double.parseDouble(p2pubValue.getText());
schoolCatchment = Double.parseDouble(p2schoolValue.getText());

housePriceFactor.setTopographyCatchmentArea(topographyCatchment);
housePriceFactor.setIndustrialsCatchmentArea(industrialsCatchment);
housePriceFactor.setTowncentreCatchmentArea(towncentreCatchment);
housePriceFactor.setPubsCatchmentArea(pubsCatchment);
housePriceFactor.setSchoolCatchmentArea(schoolCatchment);

Simulator s = new Simulator(50,50,gui);
}

if(event.getSource() == p3button){

SimulateHousePrice simulateHousePrice = new SimulateHousePrice();
long housePrice = simulateHousePrice.housePrice(housePriceFactor);
long housePri = (long)(housePrice );

p3to100Value.setText((housePri*100)+"");
p3to250Value.setText((housePri*250)+"");
p3to500Value.setText((housePri*500)+"");
p3to1000Value.setText((housePri*1000)+"");
p3to1001Value.setText((housePri*1500)+"");

p3AvgPriceValue.setText(housePri+"");
}

if(event.getSource() == p3button2){

SimulateHousePrice simulateHousePrice = new SimulateHousePrice();
long housePrice = simulateHousePrice.housePrice(housePriceFactor);
int yesrs = Integer.parseInt(p3XYearSimValue.getText());

long housePri = (long)((housePrice) * yesrs);

p3to100Value.setText((housePri*100)+"");
p3to250Value.setText((housePri*250)+"");
p3to500Value.setText((housePri*500)+"");
p3to1000Value.setText((housePri*1000)+"");
p3to1001Value.setText((housePri*1500)+"");

p3AvgPriceValue.setText(housePri+"");
}

if(event.getSource() == p3button3){

System.exit(0);
}


}



public static void main(String arg[]){


gui = new HouseMarketGUI();

}

}

OUTPUTS











Read more...

Thursday, April 16, 2009

Adding logging in Java Applications using LOG4J

Step1: Create Log4J Properties File





# this logger is for application logging

log4j.rootLogger=INFO, STDOUT



# *****************************************************************

# Appender A1 - Rolling File

# *****************************************************************

# Define the actual Appender to use that is associated with our string; in this

# case we select the RollingFileAppender which writes to a file

log4j.appender.STDOUT=org.apache.log4j.RollingFileAppender


# Set properties for the RollingFileAppender

log4j.appender.STDOUT.File=.../log/Application.log


# Set the layout for the Appender

log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout

log4j.appender.STDOUT.layout.ConversionPattern=%d %-5p -[%c] %m%n


# Set max size (25 MB each file) and backup index (save 4000 files) that's 100GB!

log4j.appender.STDOUT.MaxFileSize=15MB

log4j.appender.STDOUT.MaxBackupIndex=10





Step2: PropertyConfigurator



This line in your startup java class(Main method).


PropertyConfigurator.configure(".../log/Application.log");



Step3: Declar a static variable



Declar a static variable for the class will use the log


private static final Logger LOG = Logger.getLogger(Sample.class);




Step4: write a log in your program



LOG.debug("");


or


LOG.error("");


or


LOG.warn("");


or

LOG.info("");




Step5: import Jar file for LOG4J



log4j-1.2.14.jar






LOG4J example in Java Application:



1.log4j.prperties (Use above Properties File in step1)



2.Sample.java



import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;

public class Sample

{

private static final Logger LOG = Logger.getLogger(Sample.class);


public void display(){

LOG.info("Display method");

}


public static void main(String[] args)

{

PropertyConfigurator.configureAndWatch(".../src/log4j.properties",5000);

System.out.println("Hello World!");

Sample sample = new Sample();

sample.display();

}

}


3.Download jar file (log4j-1.2.14.jar)then add it.



4.Run your application.

Read more...

Saturday, April 11, 2009

SpellChecker using Java

SpellChecker.java




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

public class SpellChecker {


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

String read = null;
String filename1 = "dictionary.txt";
FileReader fr1 = new FileReader(filename1);//read the file

BufferedReader br1 = new BufferedReader(fr1);
ArrayList al = new ArrayList();
while((read = br1.readLine()) != null){//count the line number and print the error message
al.add(read.trim());
}


String filename2 = "file.txt";
FileReader fr2 = new FileReader(filename2);//read the file

BufferedReader br2 = new BufferedReader(fr2);
ArrayList result = new ArrayList();
int line = 1;
while((read = br2.readLine()) != null){//count the line number and print the error message

StringTokenizer st = new StringTokenizer(read," ");

while(st.hasMoreTokens()){
String str = st.nextToken();
str = str.replace('(',' ');
str = str.replace(')',' ');
str = str.replace(',',' ');
str = str.replace('.',' ');
str = str.replace('/',' ');
str = str.trim();
Iterator it = al.iterator();
boolean flag = false;
while(it.hasNext()){
String dictStr = (String) it.next();

if(str.equals(dictStr)){
flag = true;
}
}

if(!flag){
result.add(str+" "+line);
}
}

line++;
}


Collections.sort(result);
Iterator it1 = result.iterator();

while(it1.hasNext()){
System.out.println(" "+it1.next());
}
}
}

dictionary.txt


enter your words one by one
example:

java
j2ee
solution

file.txt



enter your paragraph

Read more...

Tuesday, March 24, 2009

Reverse number in Java

Reverse number in Java



package ca1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReverseNumber{

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

InputStreamReader cin = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(cin);

System.out.println("Enter your value : ");
String str = br.readLine();

int i = str.length()-1;

while(0 <= i){
System.out.println(str.charAt(i));
i--;
}

}
}

Read more...

Saturday, March 21, 2009

Fahrenheit to Celsius convertor in JAVA

import java.io.*;
import java.text.*;

class FahrenheittCelsiusconvertor {

public static void main(String arg[]) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String getValue;
double fahrenheitt = 0.00;
char reply;


do {


System.out.print("\n\t FAHRENHEIT TO CELSIUS CONVERTER");
System.out.print("\n\t -------------------------------\n\n");

System.out.print("ENTER FAHRENHEIT VALUE : ");
// Input routine that will accept numerial values
getValue = stdin.readLine();
fahrenheitt = Integer.parseInt(getValue);

System.out.print("CELSIUS VALUE IS " + decimalFormat.format(fah_cel(fahrenheitt)) + "\n");

System.out.print("\nDO YOU WANT TO continue Y/N : ");
String answer = stdin.readLine();
reply = answer.charAt(0);

} while (reply == 'Y' || reply == 'y');

if (reply == 'n' || reply == 'N') {

System.exit(0);
}
}
// A method to compute the fahrenheit to
// celsius

public static double fah_cel(double f) {
double cel = 0.00;
cel = (5.0 / 9.0) * (f - 32.0);
return (cel);
}
} // End of Code

Read more...

Tuesday, March 10, 2009

Page Replacement algorithm


public class KernelFunctions
{
//******************************************************************
// Methods for supporting page replacement
//******************************************************************

// the following method calls a page replacement method once
// all allocated frames have been used up
// DO NOT CHANGE this method
public static void pageReplacement(int vpage, Process prc, Kernel krn)
{
if(prc.pageTable[vpage].valid) return; // no need to replace

if(!prc.areAllocatedFramesFull()) // room to get frames in allocated list
addPageFrame(vpage, prc, krn);
else
pageReplAlgorithm(vpage, prc, krn);
}

// This method will all a page frame to the list of allocated
// frames for the process and load it with the virtual page
// DO NOT CHANGE this method
public static void addPageFrame(int vpage, Process prc, Kernel krn)
{
int [] fl; // new frame list
int freeFrame; // a frame from the free list
int i;
// Get a free frame and update the allocated frame list
freeFrame = krn.getNextFreeFrame(); // gets next free frame
if(freeFrame == -1) // list must be empty - print error message and return
{
System.out.println("Could not get a free frame");
return;
}
if(prc.allocatedFrames == null) // No frames allocated yet
{
prc.allocatedFrames = new int[1];
prc.allocatedFrames[0] = freeFrame;
}
else // some allocated but can get more
{
fl = new int[prc.allocatedFrames.length+1];
for(i=0 ; i fl[i] = freeFrame; // adds free frame to the free list
prc.allocatedFrames = fl; // keep new list
}
// update Page Table
prc.pageTable[vpage].frameNum = freeFrame;
prc.pageTable[vpage].valid = true;
}

// Calls to Replacement algorithm
public static void pageReplAlgorithm(int vpage, Process prc, Kernel krn)
{
switch(krn.pagingAlgorithm)
{
case CLOCK: pageReplAlgorithmCLOCK(vpage, prc, krn); break;
case ECLOCK: pageReplAlgorithmECLOCK(vpage, prc, krn); break;
}
}

//--------------------------------------------------------------
// The following methods need modification to implement
// the three page replacement algorithms
// ------------------------------------------------------------
// The following method is called each time an access to memory
// is made. It will allow you
// to update the page table entries for supporting various
// page replacement algorithms.
// when write is true, the memory access performed a write to the memory location
// Note: modified bit modified by the Process class when page selection is made.
public static void doneMemAccess(int vpage, Process prc, double clock)
{
if(prc.pageTable[vpage].valid)
{
prc.pageTable[vpage].used = true;
prc.pageTable[vpage].tmStamp = clock;
}
}

// CLOCK page Replacement algorithm
public static void pageReplAlgorithmCLOCK(int vpage, Process prc, Kernel krn)
{
int vPageReplaced; // Page to be replaced
int frame; // frame to receive new page
// Find page to be replaced
boolean flag = true;
while(flag)
{
frame = prc.allocatedFrames[prc.framePtr]; // frame in buffer
vPageReplaced = findvPage(prc.pageTable,frame);
if(prc.pageTable[vPageReplaced].used)
{
prc.pageTable[vPageReplaced].used = false;
}
else // found a replacement page
{
if(prc.pageTable[vPageReplaced].modified) krn.numReplModified++; // Increment count
prc.pageTable[vPageReplaced].valid = false; // replacing the page
prc.pageTable[vpage].frameNum = frame; // load page into the frame and update table
prc.pageTable[vpage].valid = true; // make the page valid
flag = false;
}
prc.framePtr = (prc.framePtr+1) % prc.allocatedFrames.length; // point to next frame in list
}
}

// Enhanced CLOCK page Replacement algorithm
public static void pageReplAlgorithmECLOCK(int vpage, Process prc, Kernel krn)
{
/* Complete */
}

// finds the virtual page loaded in the specified frame fr
public static int findvPage(PgTblEntry [] ptbl, int fr)
{
int i;
for(i=0 ; i {
if(ptbl[i].valid)
{
if(ptbl[i].frameNum == fr)
{
return(i);
}
}
}
System.out.println("Could not find frame number in Page Table "+fr);
return(-1);
}


// *******************************************
// The following method is provided for debugging purposes
// Call it to display the various data structures defined
// for the process so that you may examine the effect
// of your page replacement algorithm on the state of the
// process.
// Method for displaying the state of a process
// *******************************************
public static void logProcessState(Process prc)
{
int i;

System.out.println("--------------Process "+prc.pid+"----------------");
System.out.println("Virtual pages: Total: "+prc.numPages+
" Code pages: "+prc.numCodePages+
" Data pages: "+prc.numDataPages+
" Stack pages: "+prc.numStackPages+
" Heap pages: "+prc.numHeapPages);
System.out.println("Simulation data: numAccesses left in cycle: "+prc.numMemAccess+
" Num to next change in working set: "+prc.numMA2ChangeWS);
System.out.println("Working set is :");
for(i=0 ; i {
System.out.print(" "+prc.workingSet[i]);
}
System.out.println();
// page Table
System.out.println("Page Table");
if(prc.pageTable != null)
{
for(i=0 ; i {
if(prc.pageTable[i].valid) // its valid printout the data
{
System.out.println(" Page "+i+"(valid): "+
" Frame "+prc.pageTable[i].frameNum+
" Used "+prc.pageTable[i].used+
" count "+prc.pageTable[i].count+
" Time Stamp "+prc.pageTable[i].tmStamp);
}
else System.out.println(" Page "+i+" is invalid (i.e not loaded)");
}
}
// allocated frames
System.out.println("Allocated frames (max is "+prc.numAllocatedFrames+")"+
" (frame pointer is "+prc.framePtr+")");
if(prc.allocatedFrames != null)
{
for(i=0 ; i System.out.print(" "+prc.allocatedFrames[i]);
}
System.out.println();
System.out.println("---------------------------------------------");
}
}

// Page Table Entries
class PgTblEntry
{
int frameNum; // Frame number
boolean valid; // Valid Bit
boolean used; // Used Bit
boolean modified; // Modified bit
double tmStamp; // Time Stamp
long count; // for counting
}

------------------------------

//******************************************************
import java.util.*;
import java.util.concurrent.*;
import cern.jet.random.engine.*;
import cern.jet.random.*;
import EvSchedSimul.*;
//
// Some enumeration types
enum Kaction { ACCESSING, MEMACCESS, PAGEFAULT, IDLE }; // Addressing actions possible by kernel
enum PagingAlgorithm { FIFO, LRU, CLOCK, ECLOCK }; // For definining paging algorithm used.

// The Simulation model Class
class MemManage extends EvSched // Event Scheduling Simulation program
{
// Constants (time units is microseconds
final double FaultTime = 100; // Time for faults 100 time units
final double MemTime = 1; // Time for acessing memory 1 time unit
final int NumFrames = 32; // number of physical frames
final int MeanMemAccesses = 20; // mean number of memory accesses per process execution cycle
/* Parameter */
// Paging algorithm set in the Kernel Class

/* Data Modules for implementing timing maps */
Poisson memoryAccesses; // for defining number of memory accesses by a process
MersenneTwister writeToPage; // Defines if page is dirty after page fault;

/* Resource Entity - the kernel */
Kernel kernel;

/* Aggregate Entities */
ConcurrentLinkedQueue readyQueue; // process ready queue
HashSet ioQueue; // IO queue implemented as a set (to make code clearer)

/* Output Sets */
ESOutputSet phiTimeBtwFaults; // Sample Set
int numMemAccesses; // Number of memory accesses with no page faults
long numPer1000; // number of accesses per 1000
long numReplModified; // number of modified pages

// Methods
// Model Behaviour
// Constructor - Also nitialises the model
public MemManage(PagingAlgorithm pgAlg, double t0time, double tftime, Seeds sd)
{
Process prc;
int pid = 100;

// Set up distribution functions
memoryAccesses = new Poisson(MeanMemAccesses,
new MersenneTwister(sd.mAcc));

// System Initialization
readyQueue = new ConcurrentLinkedQueue();
ioQueue = new HashSet();
// Lets do processes
prc = new Process(pid++, 10,8,6,6,250,sd.prc1,sd.maprc1,sd.bernprc1); // 30 pages
kernel = new Kernel(NumFrames, pgAlg);
kernel.processExecuting = prc; // Set up first process as executing
prc.numMemAccess = memoryAccesses.nextInt();
kernel.processExecuting.vpage = selectAddress(prc);
kernel.action=Kaction.PAGEFAULT;
// Other processes added to ready queue
prc = new Process(pid++, 10,6,4,4,150,sd.prc2,sd.maprc2,sd.bernprc2); // 24 pages
readyQueue.add(prc);
prc = new Process(pid++, 18,8,6,4,100,sd.prc3,sd.maprc3,sd.bernprc3); // 36 pages
readyQueue.add(prc);
prc = new Process(pid++, 12,8,6,6,300,sd.prc4,sd.maprc4,sd.bernprc4); // 32 pages
readyQueue.add(prc);

// Setup sample set
phiTimeBtwFaults = new ESOutputSet("phiTimeBtwFaults");
numMemAccesses = 0;

// Initialize the simulation model
initEvSched(t0time,tftime);

preConditions(); // check preconditions to schedule event (first page fault)
}

// Future Events
// Future Event Names (used in FEL)
final int EndPageFault=1; // End of page fault
final int EndMemoryAccess=2; // End of memory access

// Translates event id to name(for loggin)
public String getEventName(int num)
{
switch(num)
{
case EndPageFault: return("EndMemoryAccess");
case EndMemoryAccess: return("EndMemoryAccess");
}
return("Unknown");
}

public void processEvent(int fEvent, Object obj)
{
switch(fEvent)
{
case EndPageFault: endPageFault((Process)obj); break;
case EndMemoryAccess: endMemoryAccess(); break;
default: System.out.println("Bad future event" + fEvent); break;
}
}

private void endPageFault(Process cProcess) // finished a page fault operation
{
kernel.timeLastFault = clock;
KernelFunctions.pageReplacement(cProcess.vpage,cProcess,kernel);
if(!ioQueue.remove(cProcess)) System.out.println("Process "+cProcess.pid+" not in ioQueue");
else readyQueue.add(cProcess);
preConditions(); // start activities
}

private void endMemoryAccess() // endMemoryAcess SCS
{
// AccessMemory Terminating Event SCS
KernelFunctions.doneMemAccess(kernel.processExecuting.vpage,kernel.processExecuting,clock);
if(kernel.processExecuting.numMemAccess <= 0)
{
readyQueue.add(kernel.processExecuting); // adding current process to ready queue
kernel.processExecuting = (Process) readyQueue.poll();
if(kernel.processExecuting == null)
{
System.out.println("Error - no process on ready queue");
}
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
}
if(kernel.processExecuting.numMA2ChangeWS <= 0) kernel.processExecuting.updateWS();
else kernel.processExecuting.numMA2ChangeWS--;
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
preConditions(); // start activities
}

// Check for starting events
private void preConditions()
{
while(true) // loop until no preconditions are true
{
if(kernel.action == Kaction.PAGEFAULT)
{
phiTimeBtwFaults.put(clock,clock-kernel.timeLastFault);
Process cProcess = kernel.processExecuting;
cProcess.vpageFromFault = cProcess.vpage; // flag page that caused fault
ioQueue.add(cProcess);
kernel.processExecuting = (Process) readyQueue.poll(); // Next process
if(kernel.processExecuting == null)
kernel.action = Kaction.IDLE; // no processes to execute
else
{ // Execute the next process
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
}
addEventNotice(EndPageFault,clock+FaultTime,cProcess);
}
else if(kernel.action == Kaction.MEMACCESS)
{
kernel.action = Kaction.ACCESSING;
kernel.processExecuting.numMemAccess--;
numMemAccesses++;
addEventNotice(EndMemoryAccess,clock+MemTime);
}
else if((kernel.action == Kaction.IDLE) && (readyQueue.size() !=0) ) // StartExecuting Action
{
kernel.processExecuting = (Process) readyQueue.poll(); // Next process
kernel.processExecuting.numMemAccess = memoryAccesses.nextInt();
if(kernel.processExecuting.vpageFromFault != -1)
{
kernel.processExecuting.vpage = kernel.processExecuting.vpageFromFault;
kernel.processExecuting.vpageFromFault = -1;
}
else kernel.processExecuting.vpage = selectAddress(kernel.processExecuting);
kernel.action = nextAction(kernel.processExecuting.vpage, kernel.processExecuting);
}
else break;
}
}

public boolean implicitStopCondition( ) // termination explicit
{ return(false);}

/************ Implementation User defined Modules ***********/
public int selectAddress(Process prc) // returns virtual page number being addressed
{ return prc.selectAddressPrc(); } // defined as part of the class

public Kaction nextAction(int vpage,Process prc)
{
if(prc.pageTable[vpage].valid) return(Kaction.MEMACCESS);
else return(Kaction.PAGEFAULT);
}

public void computeOutput()
{
phiTimeBtwFaults.computePhiDSOVs();
numPer1000 = (phiTimeBtwFaults.number*1000)/(numMemAccesses+phiTimeBtwFaults.number);
numReplModified = kernel.numReplModified;
}
}


// Defining the Consumer entities - the Process
class Process
{
//-----------------------------------------
// General process data structures
int pid; // Process ID
public int numPages; // Number of virtual pages
public PgTblEntry [] pageTable; // Page table
public int [] workingSet; // List of virtual pages in working set
int numAllocatedFrames; // Number of allocated physical frames
int [] allocatedFrames; // List of allocated frames - contains frame numbers
int framePtr; // index into allocatedFrames.
//-----------------------------------------
// for Simulation of process execution to create locality of reference
Poisson prcMA2ChangeWS; // for getting a discrete random number
Uniform prcDiscreteRandom; // for getting a discrete random number
Binomial prcBern; // To create Bernouilli random number generator
int numMemAccess; // number of memory accesses during a cycle executing
int numMA2ChangeWS; // number of memory accesses to change working set
public int [] wsSegments; // defines indexes in workingSet to divide into segments (code, data, etc.)
public int vpage; // virtual page being accessed
public int vpageFromFault; // virtual page just loaded after default - need to be accessed first executed.
// Mumber of pages per segment of program
int numCodePages; // Code segment
int numDataPages; // Data segment
int numStackPages; // Stack segment
int numHeapPages; // Heap segment

public Process(int pid, int nCode, int nData, int nStack, int nHeap, int meanMA, int sd1, int sd2, int sd3)
{
int i; // an index
// Setup random number generators
prcDiscreteRandom = new Uniform(new MersenneTwister(sd1));
prcMA2ChangeWS = new Poisson(meanMA,new MersenneTwister(sd2));
prcBern = new Binomial(1,0.90,new MersenneTwister(sd3));
// Setup process numbers
this.pid = pid;
numPages = nCode+nData+nStack+nHeap;
numCodePages=nCode;
numDataPages=nData;
numStackPages=nStack;
numHeapPages=nHeap;
// Setup the page table entry - all invalid
pageTable = new PgTblEntry[numPages];
for(i = 0 ; i {
pageTable[i] = new PgTblEntry();
pageTable[i].valid = false;
pageTable[i].used = false;
pageTable[i].tmStamp = 0;
}
allocateFrames(); // Allocates frames - current fixed allocation
// Setup working set and list to generate page references
wsSegments = new int[7]; // 0 - end of code 1 - end of data 2 - end of stack 3 - end of heap
// 4 - next section to address.
// 5,6 - pages to create locality of reference
updateWS(); // Sets up the working set
}

public void updateWS()
{
int ncode, ndata, nstack, nheap; // number of pages in each segment
int ix; // index into working set
int i;

// Radomly select number of pages from each segment
ncode = prcDiscreteRandom.nextIntFromTo(1, (numCodePages/2));
ndata = prcDiscreteRandom.nextIntFromTo(1, (numDataPages/2));
nstack = prcDiscreteRandom.nextIntFromTo(1, (numStackPages/2));
nheap = prcDiscreteRandom.nextIntFromTo(1, (numHeapPages/2));
if(ncode == 0) ncode = 1;
if(ndata == 0) ndata = 1;
if(nstack == 0) nstack = 1;
if(nheap == 0) nheap = 1;

workingSet = new int[ncode+ndata+nstack+nheap];
ix = 0;
for(i=0 ; i { workingSet[ix] = getPageNumforWS(0,numCodePages-1,workingSet,ix); ix ++; }
wsSegments[0] = ix-1; // defines how many code pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages,numCodePages+numDataPages-1,workingSet,ix); ix ++; }
wsSegments[1] = ix-1; // defines how many data pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages+numDataPages,
numCodePages+numDataPages+numStackPages-1,
workingSet,ix);
ix ++; }
wsSegments[2] = ix-1; // defines how many stack pages are in working set
for(i=0 ; i { workingSet[ix] = getPageNumforWS(numCodePages+numDataPages+numStackPages,
numCodePages+numDataPages+numStackPages+numHeapPages-1,
workingSet,ix);
ix ++; }
wsSegments[3] = ix-1; // defines how many heap pages are in working set
wsSegments[4] = 0; // start with a code page
numMA2ChangeWS = prcMA2ChangeWS.nextInt(); // Number of references before changing working set
}

private int getPageNumforWS(int start, int end, int [] list, int len)
{
int num;
while(true)
{ // Keep asking for number until one not in list found
// This can take a while if numbers in list contains
// most of the numbers being selected AND an
// infinite loop if all numbers are in the list
num = prcDiscreteRandom.nextIntFromTo(start,end);
if(notInIntArray(num,list,len)) return(num);
}
}

private boolean notInIntArray(int i, int [] array, int len)
{
int ix;
for(ix = 0 ; ix < len ; ix++)
{ if(array[ix] == i) return(false); }
return(true);
}

// Address is selected from code, data, stack and heap sections of the working
// set - this to improve locality of reference
public int selectAddressPrc()
{
int start;
int end;
int num;
int pageSelected;
// Define start index and end index of segment into Working set
// Skip if 0 or 1 - code or data segments
if((areAllocatedFramesFull()) && (prcBern.nextInt() == 1))
{ // Select from the allocated pages
num = prcDiscreteRandom.nextIntFromTo(5,6); // using code and other page
pageSelected = wsSegments[num]; // reusing pages
}
else
{// Select from the working set
if(wsSegments[4] == 0) start = 0; // Start
else start = wsSegments[wsSegments[4]-1]+1;
end = wsSegments[wsSegments[4]]; // End

// Randomly select a page from the segment in working set
if( (end-start)==0) // only one page - no need to select
{
pageSelected = workingSet[end];
}
else
{
num = prcDiscreteRandom.nextIntFromTo(start,end);
pageSelected = workingSet[num];
}
if(wsSegments[4] == 0) // code segment
{
wsSegments[5] = pageSelected;
pageTable[pageSelected].modified=false; // code note modified
}
else // other segment
{
wsSegments[6] = pageSelected;
pageTable[pageSelected].modified=true; // modify data, stack, heap
}
wsSegments[4] = (wsSegments[4]+1)%4;
}
return(pageSelected);
}

public boolean areAllocatedFramesFull()
{
if(allocatedFrames == null) return(false);
if(allocatedFrames.length < numAllocatedFrames) return(false);
return(true);
}

//******************************************************************
// Methods for supporting allocation schemes
//******************************************************************
public void allocateFrames()
{
numAllocatedFrames = 5;
allocatedFrames = null; // no frames allocated yet
framePtr = 0; // point to the first entry - not used until allocateFrames is filled
// This is to support FIFO replacement algorithm
}
}

// Defining the Resource entity - the kernel
class Kernel
{
public int numFrames;
public int [] freeList;
public Process processExecuting; // executing process
public Kaction action ; // Action to be taken - set to:
// ACCESSING - in the middle of accessing memory
// MEMACESS - next action is to access memory no page fault
// PAGEFAULT - next action is to access memory with page fault
double timeLastFault; // time of last page fault.
PagingAlgorithm pagingAlgorithm;
long numReplModified=0; // number of modified pages - for recording

public Kernel(int numFrames, PagingAlgorithm pgAlg)
{
int i;
pagingAlgorithm = pgAlg;
timeLastFault = 0;
action = Kaction.PAGEFAULT;
this.numFrames = numFrames;
freeList = new int [numFrames];
for(i=0 ; i }

public int getNextFreeFrame()
{
int [] fl;
int freeFrame;
int i;

if(freeList == null) return(-1); // list is empty return -1
freeFrame = freeList[0]; // gets next free frame
// Update the freeList (removes the head)
fl = new int[freeList.length-1];
if(freeList.length == 1) freeList = null;
else
{
for(i=0 ; i freeList = fl;
}
// Return free frame
return(freeFrame);
}

public void returnFrame2FreeList(int fr)
{
int [] fl; // to create new free list
int i;

// Update the freeList (removes the head)
if(freeList == null)
{
freeList = new int[1];
freeList[0] = fr;
}
else
{
fl = new int[freeList.length+1]; // create new list and copy current list
for(i=0 ; i fl[i] = fr; // appends newly released frame
freeList = fl;
}
}

}

class Seeds
{
int mAcc; // for number of memory accesses
int dRand; // kernel random number generator
int prc1; // process 1 random number generator
int prc2; // process 2 random number generator
int prc3; // process 3 random number generator
int prc4; // process 4 random number generator
int maprc1; // process 1 random number generator
int maprc2; // process 2 random number generator
int maprc3; // process 3 random number generator
int maprc4; // process 4 random number generator
int bernprc1; // process 1 random number generator
int bernprc2; // process 2 random number generator
int bernprc3; // process 3 random number generator
int bernprc4; // process 4 random number generator

public Seeds(int sd1,int sd2, int sd3, int sd4, int sd5, int sd6,
int sd7,int sd8, int sd9, int sd10, int sd11, int sd12,
int sd13, int sd14)
{
mAcc=sd1;
dRand=sd2;
prc1=sd3;
prc2=sd4;
prc3=sd5;
prc4=sd6;
maprc1=sd7;
maprc2=sd8;
maprc3=sd9;
maprc4=sd10;
bernprc1=sd11;
bernprc2=sd12;
bernprc3=sd13;
bernprc4=sd14;
}
}

------------------------

// File: MemManageExp.java
// Description:
// Simulation of memory management system

import cern.jet.random.engine.*;

// Main Method: Experiments
//
class MemManageExp
{
public static void main(String[] args)
{
double startTime=0.0, endTime=5000000; // 5 seconds
Seeds sds;
MemManage mmng;

// Lets get a set of uncorrelated seeds
RandomSeedGenerator rsg = new RandomSeedGenerator();
sds = new Seeds( rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed());


// Use CLOCK page replacement algorithm
System.out.println("Running simulation using " + "CLOCK");
mmng = new MemManage(PagingAlgorithm.CLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
System.out.println("Number of dirty pages replaced: "+mmng.numReplModified);
System.out.println();

// Use ECLOCK page replacement algorithm
System.out.println("Running simulation using " + "CLOCK");
mmng = new MemManage(PagingAlgorithm.ECLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
System.out.println("Number of dirty pages replaced: "+mmng.numReplModified);
System.out.println();
}
}

------------------------

// File: MemManageExp.java
// Description:
// Simulation of memory management system

import cern.jet.random.engine.*;

// Main Method: Experiments
//
class EClockExp
{
public static void main(String[] args)
{
double startTime=0.0, endTime=10000; // .25 second
Seeds sds;
MemManage mmng;

// Lets get a set of uncorrelated seeds
RandomSeedGenerator rsg = new RandomSeedGenerator();
sds = new Seeds( rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed(),
rsg.nextSeed(), rsg.nextSeed());

// Loop for NUMRUN simulation runs
System.out.println("Running simulation");
mmng = new MemManage(PagingAlgorithm.CLOCK,startTime,endTime,sds);
mmng.runSimulation();
mmng.computeOutput();
System.out.println("Number of faults: "+mmng.phiTimeBtwFaults.number);
System.out.println("Number memory accesses (no faults): "+mmng.numMemAccesses);
System.out.println("Number of faults per 1000 references: "+mmng.numPer1000);
}
}

------------------------------

Read more...

Monday, March 9, 2009

Image process

Complete the implementation of the doFindTarget method. This task is inspired by the Where's Waldo franchise (also known by different names in different countries), in which you must find a little image of Waldo hidden in a much bigger picture.

To avoid infringing on the Waldo trademark/copyright, I have initialized a tiny picture of myself in the Picture object targetPic. Your method should find the targetPic (or the closest match) in the image and draw a red box around where the targetPic would fit best on the myPic image. Note that parts of the targetPic might be obscured, and the targetPic is allowed to be as much as one-half of its height and width outside of the frame of the main image.
There are many different ways to try to find an image hidden in another image (and this is still an active area of research). For this problem, you must use the following basic approach: for each possible position that the targetPic might be in the main image, you should compute some score of how well the targetPic matches the main image at that position. You must search every possible position, and find the position with the best score. You then draw the red box around that position.
I have provided a helper method computeMatch to compute a score. You are welcome to use this, or to create a different scoring function of your own. But whatever you do, it must be effective at finding the image!


Create a new method to do your solution, so that your doFindTarget method can be marked for normal credit. Your method must start with the word do and you should follow the convention of capitalizing the first character of each word in the method name just as was done for the other methods, e.g., doFasterFindTarget or doBetterFindTarget. Your method can take any number of int or double parameters (or no parameters at all) but must not take parameters of any other type. If your method takes parameters, you should include a parameter annotation for each of them as follows:
public void doMyMethod( @ParamDescrip( "description of first parameter" ) int myFirstParam,
@ParamDescrip( "description of second parameter" ) double mySecondParam )
{


}
Be sure to include the valid range of values (if any) in the parameter description (e.g., @ParamDescrip( "alpha value (0-255)" ) )
Technical point: Annotations are not normally needed on parameters. They're added here so that the application can figure out how to prompt the user appropriately. Remember that when this application was written, it had no idea what method you would write for this assignment, so it had no way of knowing in advance how to prompt the user!

If you are trying to make your method run much faster, test it on the larger images from the doFindTarget part of this assignment.
If you are trying to make a more sophisticated target finder, here are some small test images where a human would spot the target image instantly, but the computeMatch method I supplied doesn't find the image: test-color.jpg (actually, my doFindTarget works on this image, much to my surprise), t




--------------



import java.awt.Graphics;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.net.URL;

import com.sun.media.jai.widget.DisplayJAI;

import picUtil.ParamDescrip;

import picUtil.Picture;

import picUtil.Pixel;

import picUtil.PixelColour;

import sun.misc.GC;



/**

* This class represents a simple image processor that performs basic image

* manipulations.

*

*/

public class PictureProcessor {

/** The picture associated with this processor. */

private Picture myPic;

/** The target image for the doFindTarget method. */

private Picture targetPic;

/**

* Constructs a picture processor that manipulates a default image.

*/

public PictureProcessor() {

URL imgURL = getClass().getResource("/image/betty.jpg");

myPic = new Picture(imgURL);

URL targetURL = getClass().getResource("/image/AlanTarget.gif");

targetPic = new Picture(targetURL);

// The picUtil package seems to have a bug in

// handling the alpha channel. This is a kludge

// to fix things up... The picUtil package appears

// to take pixels that should be transparent and

// makes them pure white instead (with alpha==255,

// too). So, I'm going to take any pure white pixel

// in the target, and set the alpha to be 0.

for (int i=0; i
for (int j=0; j
Pixel thePixel = targetPic.getPixel(j,i);

PixelColour c = thePixel.getColour();

if ((c.getRed()==255) && (c.getGreen()==255) &&

(c.getBlue()==255)) c.setAlpha(0);

thePixel.setColour(c);

}

}

}

/**

* Reads a new image for processing from the specified file.

*

* @param fileName

* The name of the file to be processed.

*/

public void readImage(String fileName) {

myPic = new Picture(fileName);

}

/**

* Gets the picture processed by this picture processor.

*

* @return The picture processed by this picture processor.

*/

public Picture getPicture() {

return myPic;

}

/**

* Paints a vertical red stripe down the image from top to bottom between

* pixels 100 (inclusive) and 200 (exclusive)

*/

public void doRedStripe() {

PixelColour red = new PixelColour(255, 0, 0);

Pixel nextPixel;

for (int y = 0; y < myPic.getImgHeight(); y++) {

for (int x = 100; x < 200; x++) {

nextPixel = myPic.getPixel(x, y);

nextPixel.setColour(red);

}

}

}

/**

* Converts image to black-and-white.

*

* The preceding method and this one work on the Picture by changing the

* Pixels in it. The next method doBlur does things differently.

*

*/

public void doBW() {

// Go over full image...

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

Pixel thePixel = myPic.getPixel(j, i);

PixelColour thePixelColour = thePixel.getColour();

int aveBrightness = (int) Math.round(

(thePixelColour.getRed() + thePixelColour.getGreen() + thePixelColour.getBlue()) / 3.0);

PixelColour grey = new PixelColour(aveBrightness, aveBrightness, aveBrightness);

thePixel.setColour(grey);

}

}

}

/**

* Blurs the image by averaging RGB values in neighbourhood of specified

* size.

*

* This method is an example of a method that builds a new Picture object to

* replace the old Picture object, instead of changing the Pixels in place

* (like the preceding two methods). The reason we're doing things this way

* is because if we changed a pixel's colour in the current image, that

* change will affect the computation of the next pixel's colour. Since we

* don't want that, we do all of the neighbourhood averaging on the old

* Picture, but store the new results in a different Picture, until the very

* end, when we're done.

*

* @param size

* Size of neighbourhood in which to compute average.

*/

public void doBlur(@ParamDescrip("neighbourhood size") int size) {

Picture blurred = new Picture(myPic.getImgWidth(), myPic.getImgHeight());

// Go over full image...

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

PixelColour aveColour = averageColoursInBlock(myPic, i - size,

j - size, i + size, j + size);

blurred.getPixel(j, i).setColour(aveColour);

}

}

myPic = blurred;

}

/**

* Computes the average colour value for each colour channel (RGB) in the

* specified block of the picture. This method correctly handles blocks that

* are partially outside of the picture. If the block is completely outside

* of the picture, then the average is meaningless, and the method returns

* pure black.

*

* @param p

* The picture being worked on.

* @param minRow

* The lowest row number in the block.

* @param minCol

* The lowest column number in the block.

* @param maxRow

* The highest row number in the block.

* @param maxCol

* The highest column number in the block.

* @return The average colour of all the pixels in the block.

*/

private PixelColour averageColoursInBlock(Picture p, int minRow,

int minCol, int maxRow, int maxCol) {

// Compute average over neighborhood

int pixelCount = 0;

int redSum = 0;

int greenSum = 0;

int blueSum = 0;

int alphaSum = 0;

for (int i = minRow; i <= maxRow; i++) {

for (int j = minCol; j <= maxCol; j++) {

if ((i >= 0) && (i < p.getImgHeight()) && (j >= 0)

&& (j < p.getImgWidth())) {

pixelCount++;

Pixel thePixel = p.getPixel(j, i);

redSum += thePixel.getColour().getRed();

greenSum += thePixel.getColour().getGreen();

blueSum += thePixel.getColour().getBlue();

alphaSum += thePixel.getColour().getAlpha();

}

}

}

// Catch the case where the block is entirely outside the image.

if (pixelCount == 0)

return new PixelColour(0, 0, 0);

PixelColour aveColour = new PixelColour(

(int) Math.round((double) redSum / pixelCount),

(int) Math.round((double) greenSum / pixelCount),

(int) Math.round((double) blueSum / pixelCount),

(int) Math.round((double) alphaSum / pixelCount));

return aveColour;

}

/**

* Creates high-contrast poster effect by changing each Pixel's color values

* to either 0 or 255, depending on whether the old value was greater or

* less than the user-specified thresholds.

*

* @param redThreshold

* the red channel threshold

* @param greenThreshold

* the green channel threshold

* @param blueThreshold

* the blue channel threshold

*/

public void doThreshold(

// Don't make any changes to this parameter list!

@ParamDescrip("red threshold") int redThreshold,

@ParamDescrip("green threshold") int greenThreshold,

@ParamDescrip("blue threshold") int blueThreshold) {

// Fill in your code here!

for (int i = 0; i < myPic.getImgHeight(); i++) {

for (int j = 0; j < myPic.getImgWidth(); j++) {

Pixel thePixel = myPic.getPixel(j,i);

int rColour = thePixel.getColour().getRed();

int gColour = thePixel.getColour().getGreen();

int bColour = thePixel.getColour().getBlue();

if (rColour>redThreshold){

PixelColour redPixel= new PixelColour(255, bColour, gColour);

thePixel.setColour(redPixel);

}else{

PixelColour redPixel= new PixelColour(0, bColour, gColour);

thePixel.setColour(redPixel);

}

if (bColour>blueThreshold){

PixelColour bluePixel= new PixelColour(rColour, 255, gColour);

thePixel.setColour(bluePixel);

}else{

PixelColour bluePixel= new PixelColour(rColour, 0, gColour);

thePixel.setColour(bluePixel);

}

if (gColour>greenThreshold){

PixelColour greenPixel= new PixelColour(rColour, bColour, 255);

thePixel.setColour(greenPixel);

}else{

PixelColour greenPixel= new PixelColour(rColour, bColour, 0);

thePixel.setColour(greenPixel);

}

}

}


}

/**

* Creates a blocky poster effect by dividing the image into blockSize x

* blockSize pixel squares. All the pixels inside each square will be

* assigned the average colour of the original pixels inside the square.

*

* Note that the blockSize might not evenly divide into the image height and

* width, so there may be non-square rectangles on the edges. For this

* assignment, you are required to have the non-square blocks ONLY along the

* bottom and right edges of your image.

*

* Hint: You may want to reuse the helper method averageColoursInBlock

* above.

*

* @param blockSize

* How big the square blocks should be.

*/

public void doPixelate(@ParamDescrip("block size") int blockSize) {

// As mentioned in the assignment webpages, for

// full credit, your code should compute the average

// pixel colour only once for each *block*, instead

// of repeating the computation for each pixel.

// This will be slightly harder to write (which

// is part of why I want you to do it that way),

// and it will also run MUCH MUCH faster.

// If you program this correctly, your doPixelate

// method will take about twice as long as the

// doBW method, even with a big blockSize (like 20).

// If you do this wrong, it will be many times

// slower for a big blockSize.

// Fill in your code here!




for (int i = 0; i
for (int j = 0; j < myPic.getImgWidth(); j+=blockSize) {


PixelColour blockColour = averageColoursInBlock

(myPic, i, j, i+blockSize-1, j+blockSize-1);


for (int y=i; y<(i+blockSize-1); y++){

for (int x=j; x<(j+blockSize-1); x++){

if(y
if(x
myPic.getPixel(x, y).setColour(blockColour);

}

}

}

}

}



/**

* Does a "Where's Waldo?"-like search for the target

* image and draws a red box around it. The target

* image is in the Picture object targetPic, and it's

* initialized to a picture of Alan Hu.

*

*/

public void doFindTarget () {

// Fill in your code here!

// Feel free to use the computeMatch method below

// if you want.



URL targetURL = getClass().getResource("/image/AlanTarget.gif");

targetPic = new Picture(targetURL);

URL BerlinURL = getClass().getResource("/image/Berlin.jpg");

Picture berlinPic = new Picture(BerlinURL);



for (int i = 0; i < berlinPic.getImgHeight(); i++) {

for (int j = 0; j < berlinPic.getImgWidth(); j++) {

for (int y=i; y<(targetPic.getImgHeight()); y++){

for (int x=j; x<(targetPic.getImgWidth()); x++){


Pixel pix1= targetPic.getPixel(i, j);

Pixel pix2= berlinPic.getPixel(x,y);

if ( pix1.equals(pix2) ) {


}

}

}

}

}

}




public void paint( Graphics g ) {

g.drawRect( targetPic.getImgHeight(),

targetPic.getImgWidth(),50,10 );




}







/**

* Computes a score of how well targetPic matches up

* with myPic, if the top-left corner of targetPic

* is positioned at row i and column j of myPic.

*

* Lower scores indicate a better match.

*

* The score is the weighted average (weighted by

* the alpha value in targetPic) of the distance

* between the two colours, squared. The squaring

* penalizes larger differences more heavily than

* simply adding up the differences.

*

* @param i The row to position the top-left corner

* of myPic; can be negative.

* @param j The column to position the top-let corner

* of myPic; can be negative.

* @return The score of how well the target matches at

* that position; lower is better.

*/

private double computeMatch(int i, int j) {

double score = 0.0;

int weightTotal = 0;

for (int di=0; di
for (int dj=0; dj
if ((i+di >= 0) && (i+di < myPic.getImgHeight()) && (j+dj >= 0)

&& (j+dj < myPic.getImgWidth())) {

PixelColour imgColour = myPic.getPixel(j+dj, i+di).getColour();

PixelColour targetColour = targetPic.getPixel(dj,di).getColour();

int alpha = targetColour.getAlpha();

int diff;

int colourDistance=0;

diff = imgColour.getRed()-targetColour.getRed();

colourDistance += diff*diff;

diff = imgColour.getGreen()-targetColour.getGreen();

colourDistance += diff*diff;

diff = imgColour.getBlue()-targetColour.getBlue();

colourDistance += diff*diff;

score += colourDistance*alpha;

weightTotal += alpha;

}

}

}

if (weightTotal==0) return 1.0/0.0; // Infinity

return score/weightTotal;

}

}


-----------------------


package picApp;

import picUtil.PicFrame;

// Referenced classes of package picApp:
// PictureProcessor

public class PicProcessorApp
{

public PicProcessorApp()
{
}

public static void main(String args[])
{
PictureProcessor myProcessor = new PictureProcessor();
new PicFrame(myProcessor);
}
}
-------------------

package picUtil;


public class PixelColour
{

public PixelColour(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
alpha = 255;
}

public PixelColour(int red, int green, int blue, int alpha)
{
this(red, green, blue);
this.alpha = alpha;
}

public int getRed()
{
return red;
}

public void setRed(int red)
{
this.red = red;
}

public int getGreen()
{
return green;
}

public void setGreen(int green)
{
this.green = green;
}

public int getBlue()
{
return blue;
}

public void setBlue(int blue)
{
this.blue = blue;
}

public int getAlpha()
{
return alpha;
}

public void setAlpha(int alpha)
{
this.alpha = alpha;
}

private int red;
private int green;
private int blue;
private int alpha;
---------------------------------


package picUtil;

import java.awt.Color;

// Referenced classes of package picUtil:
// PixelColour, Picture

public class Pixel
{

Pixel(PixelColour colour, int x, int y, Picture pic)
{
this.colour = colour;
this.x = x;
this.y = y;
this.pic = pic;
}

public void setColour(PixelColour colour)
{
this.colour = colour;
updatePic();
}

public PixelColour getColour()
{
return new PixelColour(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha());
}

private void updatePic()
{
pic.setPixel(x, y, new Color(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha()));
}

private int x;
private int y;
private PixelColour colour;
private Picture pic;
--------------------------------


package picUtil;

import java.awt.Graphics;
import javax.swing.JComponent;
import picApp.PictureProcessor;

// Referenced classes of package picUtil:
// Picture

public class PictureComponent extends JComponent
{

PictureComponent(PictureProcessor picProc)
{
this.picProc = picProc;
}

void setPictureProcessor(PictureProcessor picProc)
{
this.picProc = picProc;
}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
picProc.getPicture().draw(g, getWidth(), getHeight());
}

private PictureProcessor picProc;
-----------------------------------------


package picUtil;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;

// Referenced classes of package picUtil:
// PixelColour, Pixel

public class Picture
{

public Picture(String fileName)
{
try
{
BufferedImage temp = ImageIO.read(new File(fileName));
convertToAlpha(temp);
pixels = new Pixel[img.getWidth()][img.getHeight()];
initPixels();
}
catch(IOException e)
{
System.err.println("Critical I/O error - application terminating...");
System.exit(1);
}
}

public Picture(int width, int height)
{
img = new BufferedImage(width, height, 2);
pixels = new Pixel[width][height];
initPixels();
}

public Picture(URL url)
{
try
{
BufferedImage temp = ImageIO.read(url);
convertToAlpha(temp);
pixels = new Pixel[img.getWidth()][img.getHeight()];
initPixels();
}
catch(IOException e)
{
System.err.println("Critical I/O error - application terminating...");
System.exit(1);
}
}

public int getImgHeight()
{
return img.getHeight();
}

public int getImgWidth()
{
return img.getWidth();
}

void setPixel(int x, int y, Color color)
{
img.setRGB(x, y, color.getRGB());
}

public Pixel getPixel(int x, int y)
{
return pixels[x][y];
}

void savePicture(String fileName)
{
try
{
ImageIO.write(img, "jpg", new File(fileName));
}
catch(IOException ioexception) { }
}

void draw(Graphics g, int width, int height)
{
double imgAspectRatio = (double)getImgWidth() / (double)getImgHeight();
double viewPortAspectRatio = (double)width / (double)height;
if(imgAspectRatio < viewPortAspectRatio)
width = (int)((double)height * imgAspectRatio);
else
height = (int)((double)width / imgAspectRatio);
g.drawImage(img, 0, 0, width, height, null);
}

private void convertToAlpha(BufferedImage temp)
{
img = new BufferedImage(temp.getWidth(), temp.getHeight(), 2);
for(int y = 0; y < getImgHeight(); y++)
{
for(int x = 0; x < getImgWidth(); x++)
img.setRGB(x, y, temp.getRGB(x, y));

}

}

private void initPixels()
{
for(int y = 0; y < getImgHeight(); y++)
{
for(int x = 0; x < getImgWidth(); x++)
{
Color c = new Color(img.getRGB(x, y));
PixelColour pc = new PixelColour(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
pixels[x][y] = new Pixel(pc, x, y, this);
}

}

}

private BufferedImage img;
private Pixel pixels[][];
---------------------

package picUtil;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import picApp.PictureProcessor;

// Referenced classes of package picUtil:
// PictureComponent, MethodMenuItem, FileExtension, ParamDescrip,
// Picture

public class PicFrame extends JFrame
{
private class ImageFilter extends FileFilter
{

public boolean accept(File f)
{
if(f.isDirectory())
return true;
String extension = FileExtension.getExtension(f);
if(extension != null)
return extension.equals("gif") || extension.equals("jpeg") || extension.equals("jpg") || extension.equals("bmp");
else
return false;
}

public String getDescription()
{
return "Image files";
}

final PicFrame this$0;

private ImageFilter()
{
this$0 = PicFrame.this;
super();
}

ImageFilter(ImageFilter imagefilter)
{
this();
}
}

private class MenuActionListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
MethodMenuItem menuItem = (MethodMenuItem)e.getSource();
try
{
Object params[] = getParameterData(menuItem.getMethod());
menuItem.getMethod().invoke(processor, params);
picComp.repaint();
}
catch(NumberFormatException exc)
{
JOptionPane.showMessageDialog(PicFrame.this, "Input data not valid for parameter type.");
}
catch(Exception exc)
{
JOptionPane.showMessageDialog(PicFrame.this, "Unable to perform action.");
exc.getCause().printStackTrace();
}
setCursor(oldCursor);
}

private Object[] getParameterData(Method m)
{
Object paramVals[] = (Object[])null;
Type types[] = m.getGenericParameterTypes();
if(types.length != 0)
{
paramVals = new Object[types.length];
Annotation annots[][] = m.getParameterAnnotations();
for(int index = 0; index < types.length; index++)
paramVals[index] = promptForParameterValue(types[index], annots[index]);

}
return paramVals;
}

private Object promptForParameterValue(Type type, Annotation annots[])
{
String typeName = type.toString();
String paramDescrip = null;
for(int index = 0; index < annots.length; index++)
{
if(!(annots[index] instanceof ParamDescrip))
continue;
paramDescrip = ((ParamDescrip)annots[index]).value();
break;
}

String value = JOptionPane.showInputDialog(PicFrame.this, (new StringBuilder("Enter ")).append(paramDescrip).append(" (").append(typeName).append(")").toString(), "Enter parameter value", 3);
Object retVal = parseToType(type, value);
return retVal;
}

private Object parseToType(Type type, String value)
{
Object retVal = null;
String typeName = type.toString();
if(typeName.equals("double"))
retVal = Double.valueOf(Double.parseDouble(value));
else
if(typeName.equals("int"))
retVal = Integer.valueOf(Integer.parseInt(value));
return retVal;
}

final PicFrame this$0;

private MenuActionListener()
{
this$0 = PicFrame.this;
super();
}

MenuActionListener(MenuActionListener menuactionlistener)
{
this();
}
}

private class OpenListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser(".");
FileFilter filter = new ImageFilter(null);
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(PicFrame.this);
if(returnVal == 0)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
processor.readImage(chooser.getSelectedFile().getAbsolutePath());
picComp.repaint();
setCursor(oldCursor);
}
}

final PicFrame this$0;

private OpenListener()
{
this$0 = PicFrame.this;
super();
}

OpenListener(OpenListener openlistener)
{
this();
}
}

private class SaveAsListener
implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
int overwriteDecision = 0;
JFileChooser chooser = new JFileChooser(".");
FileFilter filter = new ImageFilter(null);
chooser.setFileFilter(filter);
int returnVal = chooser.showSaveDialog(PicFrame.this);
if(returnVal == 0)
{
File selected = chooser.getSelectedFile();
String extension = FileExtension.getExtension(selected);
String fileName = selected.getAbsolutePath();
if(extension == null)
fileName = (new StringBuilder(String.valueOf(fileName))).append(".jpg").toString();
else
if(!extension.equals("jpg") && !extension.equals("jpeg"))
fileName = (new StringBuilder(String.valueOf(fileName))).append(".jpg").toString();
if((new File(fileName)).exists())
{
Object options[] = {
"Yes", "No"
};
overwriteDecision = JOptionPane.showOptionDialog(PicFrame.this, "Overwrite existing file?", "Caution!", -1, -1, null, options, options[1]);
}
if(overwriteDecision == 0)
{
Cursor oldCursor = getCursor();
setCursor(new Cursor(3));
processor.getPicture().savePicture(fileName);
setCursor(oldCursor);
}
}
}

final PicFrame this$0;

private SaveAsListener()
{
this$0 = PicFrame.this;
super();
}

SaveAsListener(SaveAsListener saveaslistener)
{
this();
}
}


public PicFrame(PictureProcessor processor)
{
int WIDTH = 800;
int HEIGHT = 600;
this.processor = processor;
setLocationRelativeTo(null);
UIManager.put("Button.defaultButtonFollowsFocus", Boolean.valueOf(true));
picComp = new PictureComponent(processor);
setTitle("Image Processor");
setLayout(new BorderLayout());
add(picComp, "Center");
setPreferredSize(new Dimension(800, 600));
Point loc = getLocation();
loc.x -= 400;
loc.y -= 300;
setLocation(loc);
setDefaultCloseOperation(3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(initFileMenu());
menuBar.add(initActionMenu());
setJMenuBar(menuBar);
pack();
setVisible(true);
}

private JMenu initFileMenu()
{
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(new OpenListener(null));
fileMenu.add(openItem);
JMenuItem saveAsItem = new JMenuItem("Save As (jpg)");
saveAsItem.addActionListener(new SaveAsListener(null));
fileMenu.add(saveAsItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e)
{
dispose();
}

final PicFrame this$0;


{
this$0 = PicFrame.this;
super();
}
}
);
fileMenu.add(exitItem);
return fileMenu;
}

private JMenu initActionMenu()
{
JMenu actionMenu = new JMenu("Action");
MenuActionListener menuActionLstnr = new MenuActionListener(null);
Class c = processor.getClass();
Method allMethods[] = c.getMethods();
Method amethod[];
int j = (amethod = allMethods).length;
for(int i = 0; i < j; i++)
{
Method m = amethod[i];
String name = m.getName();
if(name.startsWith("do"))
{
MethodMenuItem item = new MethodMenuItem(parseName(name), m);
item.addActionListener(menuActionLstnr);
actionMenu.add(item);
}
}

return actionMenu;
}

private String parseName(String methodName)
{
String name = methodName.substring(2);
String menuName = new String();
int index = 1;
menuName = (new StringBuilder(String.valueOf(menuName))).append(name.charAt(0)).toString();
for(; index < name.length(); index++)
{
char nextChar = name.charAt(index);
if(nextChar >= 'A' && nextChar <= 'Z')
menuName = (new StringBuilder(String.valueOf(menuName))).append(" ").toString();
menuName = (new StringBuilder(String.valueOf(menuName))).append(nextChar).toString();
}

return menuName;
}

private PictureComponent picComp;
private PictureProcessor processor;


}
-------------------------

Read more...

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP