Conor Mac Aoidh
http://macaoidh.name
conor@macaoidh.name
 

Search

Archives

  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008

Spam

3,960 spam comments
blocked by
Akismet

Tag Cloud

    bt broadband CMS conor's management system conormacaoidh conor mac aoidh content management system drums fast Fedora fedora 10 furasta furasta cms furasta org gnome guide hello world HTML icsp iPhone jar Java javascript joomla kde Linux Mandriva mc kennas Monaghan Music mysql php Scratch stealing the ceiling The Dominican Affair the pot smoking pirates the strats tutorial Twitter updates web design forum webme webworks weekly tweets Windows wordpress

Ads

Java – Drawing Squares

Posted Dec 5th, 2009 by Conor in in College, Java, Languages

This weeks ICSP assignment was to write a program which draws squares. The task was to draw squares from a set list in an array, but I opted rather to accept a command line argument in my script. To write this I had to delve back into regular expression, which I hate because I don’t understand!

The program source is below. You should execute the program from the command line giving the with and height of the square you wish to draw, for example:

java Squares 4x4

And the code:

import java.lang.String;
import java.util.regex.*;

public class Squares{
        public int dimensions[];

        public Squares(String[] args){
                if(args.length==1){
                        Pattern form=Pattern.compile("^\\S+x\\S+$");
                        Matcher fit=form.matcher(args[0]);
                        if(fit.matches()){
                                try{
                                        String[] dims=args[0].split("x");
                                        int width=Integer.parseInt(dims[0]);
                                        int height=Integer.parseInt(dims[1]);
                                        this.dimensions=new int[] {width,height};
                                }
                                catch(NumberFormatException e){
                                        System.err.println("Argument must be a string, width by height, in the form 6x6");
                                        System.exit(1);
                                }
                        }
                        else{
                                System.out.println("Argument must be a string, width by height, in the form 6x6");
                                System.exit(1);
                        }
                }
                else{
                        System.err.println("Please supply an argument, which must be a string, width by height, in the form 6x6");
                        System.exit(0);
                }
        }

        public String draw(){
                int i;
                int z;
                int width=this.dimensions[0];
                int height=this.dimensions[1];
                String square="";

                for(i=0;i<height ;i++){
                        for(z=0;z<width;z++){
                                if((i==0||i==height-1)&&(z==0||z==width-1))
                                        square+="+";
                                else if(z==0||z==width-1)
                                        square+="|";
                                else if((i==0||i==height-1))
                                        square+="-";
                                else
                                        square+=" ";
                        }
                        square+="\n";
                }

                return square;
        }

        public static void main(String[] args){
                Squares square=new Squares(args);
                String draw=square.draw();
                System.out.println(draw);
        }
}
No responses yet

Java – Calculate Taxi Fares

Posted Dec 2nd, 2009 by Conor in in College, Java, Languages

This week my ICSP assignment was to calculate taxi fares. The task was:

Using the fare table write a program that calculates the fares and test if it is correct. Upload your .java or your Scratch file. A template file for java will be provided. (Hint, only the boundary values needs to be tested. The fare table is also presented in the slides. The compile command for java should be “javac TaxiRide.java”)

Fare table
Distance (km) Cost (€)
>50 30
50-100 25, plus 9 for each km > 50
100 – 2000 190, plus 8 for each km > 100
> 2000 1800

It wasn’t the hardest task. The only thing that confused me was the Java switch syntax. In PHP you can have conditions in a switch statement such as:

<?php
switch($num){
        case ($num<10):
                // blah
        break;
        case ($num<100):
                // blah
        break;
        default:
                //blah
?>

I couldn’t get Java to accept anything other than a value for the variable bring switched. So I did it the old-fashioned way! My code is below…

public class TaxiRide{
        public int distance=0;

        public TaxiRide(String arg){
                try{
                        int distance=Integer.parseInt(arg);
                        this.distance=distance;
                }
                catch(NumberFormatException e){
                        System.err.println("Arguement must be an integer representing the distance traveled");
                        System.exit(1);
                }
        }

        public int calculateFare(){
                int distance=this.distance;
                int fare=0;
                int i=0;
                if(distance<50){
                        return 30;
                }
                if(distance%lt;100){
                        fare=25;
                        distance-=50;
                        for(i=0;i<distance;i++){
                                fare+=9;
                        }
                        return fare;
                }
                if(distance<2000){
                        fare=190;
                        distance-=100;
                        for(i=0;i<distance;i++){
                                fare+=8;
                        }
                        return fare;
                }
                return 1800;
        }

        public static void main(String[] args){
                TaxiRide taxiRide = new TaxiRide(args[0]);
                int fare=taxiRide.calculateFare();
                System.out.println("The fare is: "+fare+" euro for traveling "+taxiRide.distance+"kM\n Thank you\n");
        }
}

I feel i am learning a lot from this course. Lately I have been experimenting in a few different languages. I added a bit to the Scratch Linux installer, written in Perl, so that it added an icon in the applications menu during installation. I’ve also been messing around with bash, trying to automate some of my most common commands… was thinking of writing a small bash script that backed up my data when my external hard drive is plugged in, similar to Time Machine on OSX.

No responses yet

Java – Project Euler Multiples

Posted Nov 21st, 2009 by Conor in in Java, Languages

This weeks ICSP assignment was one of the Project Euler challenges. Here is the task:

This weeks Bonus Task is to solve the First Problem using Java:
“If we list all the natural numbers below 10 that are multiples of 3
or 5, we * get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.”

In the code below, I have achieved this objective and also expanded on it. My program allows you to pass on two multiples and a max integer value to the program for which to calculate the results. You can execute:

java Multiples 3 5 1000

That command will find the sum of multiples of 3 and 5 below 1000, as stated in the task. You can also change the values to calculate different sums. The code for Multiples.java is below:

/*
 * Developer:   Conor Mac Aoidh
 * Homepage:    http://blog.macaoidh.name/2009/11/21/java-project-euler-multiples/
 */

public class Multiples{
        public static void main(String[] args){
                Multiples multiples=new Multiples();
                int one=0;
                int two=0;
                int max=0;
                if(args.length==3){
                        try{
                                one=Integer.parseInt(args[0]);
                                two=Integer.parseInt(args[1]);
                                max=Integer.parseInt(args[2]);
                        }
                        catch(NumberFormatException e){
                                System.err.println("Argument must be an integer");
                                System.exit(1);
                        }
                }
                else
                        System.out.println("You must supply integers in the format:\n multiple_one multiple_two max_integer");

                int sum=multiples.sum(one,two,max);

                System.out.println("Find the sum of all the multiples of "+one+" or "+two+" below "+max);
                System.out.println("Sum:"+sum);
        }

        public int sum(int one,int two,int max){
                int i=0;
                int sum=0;
                for(i=0;i<max ;i++){
                        if(i % one==0)
                                sum=sum+i;
                        if(i % two==0)
                                sum=sum+i;
                }
                return sum;
        }
}

Simple as that!

3 responses so far

Java Visual Hello World Popup

Posted Nov 15th, 2009 by Conor in in College, Java, Languages

I spent yesterday going a bit deeper into Java with one of my lecturers. I decided to try and write a more complicated hello world app. It’s quite simple really once you get around the strict OOP and different syntax… This is how I did it:

First you need to import some of the java libraries that we will be using:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

Then add the class, Popup. Make sure to name the file Popup.java

public class Popup{
private JFrame frame=new JFrame("Hello!");
private JPanel panel=new JPanel();
private JButton button=new JButton("Say Hello");
private JLabel label=new JLabel("Click the button to say hello...",SwingConstants.CENTER);
private ButtonListener buttonListener=new ButtonListener();

What that actually means is create a new instance of JFrame, JPanel, JButton and JLabel and store them in the frame,panel, button and label variables. As for the ButtonListener, we will deal with that later. Now we will deal with the launchFrame function which does what it says on the tin – launches the frame! Basically it just connects all of the pieces of information stored into the variables above and displays them together.

public void launchFrame(){
int height=400, width=600;
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Above we create two new integers which store the width and height of our frame. The next line sets the variables to the frame size. The final line tells the Java application to close when the window, or JFrame, is closed. Now that we have the configuration out of the way we can move on to adding the variables to the frame.

frame.getContentPane().add(label,BorderLayout.CENTER);
panel.add(button);
frame.getContentPane().add(panel,BorderLayout.WEST);
button.addActionListener(buttonListener);
frame.setVisible(true);
}

The code above adds the label to the frame, then adds the button to the panel and then the panel to the frame. Once again disregard the button.addAction.. line for now. The final line simply sets the frame to visible so we can see it.

Now that we have the frame settled, we need to add our essential main function to start up the execution:

public static void main(String args[]){
Popup popup=new Popup();
popup.launchFrame();
}
}

This code basically creates an instance of our class, Popup and then executes the function launchFrame which we have created in that class.

That’s the guts of it, but now we need to talk about these lines:

private ButtonListener buttonListener=new ButtonListener();
 public void launchFrame(){
....
button.addActionListener(buttonListener);

Basically we have previously created a button, but these lines define what happens when the button is pressed. The second line of code tells the machine to listen out for the clicking of the button, and when that happens to execute the variable buttonListener. We have created the variable buttonListener, which creates a new instance of the ButtonListener class which we have yet to create.

That is the next step, to create that class. Create a new file called ButtonListener.java and add this code:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonListener implements ActionListener{

The first four lines import the libraries that we are using. The final line is important. It states that our class, ButtonListener is implementing the ActionListener class. Below is the content of our new class:

private JFrame pressed=new JFrame("Hello World!");
public void actionPerformed(ActionEvent actionEvent){

First, we create a new JFrame for our popup just like we did in the other file. The function actionPerformed is a function from the ActionListener class that we are implementing. The parameters for the function are predefined so we need them. The rest of the code is very similar to the previous code so I won’t explain it in depth. Basically it just configures the new frame, adds the label and then displays it:

int height=160, width=200;
pressed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel pressedtext=new JLabel("Hello World!",SwingConstants.CENTER);
pressed.getContentPane().add(pressedtext,BorderLayout.CENTER);
pressed.setSize(width,height);
pressed.setVisible(true);
}

Save that file and then compile both files by executing:

javac ButtonListener.java Popup.java

Now if you run the program you should see a nice visual dialogue:

java Popup

You can download a jar archive of the program here.

The full code is below. Popup.java:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class Popup{
        private JFrame frame=new JFrame("Hello!");
        private JPanel panel=new JPanel();
        private JButton button=new JButton("Say Hello");
        private JLabel label=new JLabel("Click the button to say hello...",SwingConstants.CENTER);
        private ButtonListener buttonListener=new ButtonListener();

        public void launchFrame(){
                int height=400, width=600;
                frame.setSize(width,height);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(label,BorderLayout.CENTER);
                panel.add(button);
                frame.getContentPane().add(panel,BorderLayout.WEST);
                button.addActionListener(buttonListener);
                frame.setVisible(true);
        }

        public static void main(String args[]){
                Popup popup=new Popup();
                popup.launchFrame();
        }
}

ButtonListener.java:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonListener implements ActionListener{
        private JFrame pressed=new JFrame("Hello World!");

        public void actionPerformed(ActionEvent actionEvent){
                int height=160, width=200;
                pressed.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JLabel pressedtext=new JLabel("Hello World!",SwingConstants.CENTER);
                pressed.getContentPane().add(pressedtext,BorderLayout.CENTER);
                pressed.setSize(width,height);
                pressed.setVisible(true);
        }

}
3 responses so far
Next Entries »



Conor's Blog is powered by Wordpress | Template design by Conor Mac Aoidh