First Week of Javahackercoding

Last Thursday was my first Java class in my TAFE programming course. I wasn’t sure how I’d go, but I was feeling quite positive going into it, because I’ve been waiting to start for so long.

It was daunting.

My lecturer was shocked that I have no programming experience going into his class (I was told I should be able to catch up), and implied it was a certainty he would have to take time away from his other students to help me out. My other classmates were also surprised that I’m starting where I am.

It left me wondering if I should wait another semester and start with Visual Basic like I’m supposed to, or take the Friday morning VB class, and work late three nights to make up the time. On the other hand, I’m kinda keen to just power forward and show everyone that I can do it1 .

So I’ve had a look at this weeks homework, to better gauge how I might go, and it’s pretty straight forward. I’m sure the terminology will click eventually (here’s hoping), but the actual exercises were easy enough. I’m missing the text book I need to do the reading I should do, but I’ve got the basics of Netbeans down (starting a project, creating a class), and I’ve done all the exercises I can do without the book.

Included below is my final exercise for this week. The brief was as follows.

A farmer has a small field that is 124 metres by 332 metres. The farmer wants to plant tomatoes in his field. It is possible to put 5 plants in every square metre. Each plant costs 95cents. Write a small program that calculates the number of plants that will go into the field and the resulting cost.

And this was my solution:

``````
public class Tomatoes {
/**
* @param args the command line arguments
*/
public static void main(String [] args) {
int plantCost = 93;
double xSide = 124.27473984;
double ySide = 332.236238764;
int plantsPerSquareMeter = 5;
int totalPlants;
int totalCost;

totalPlants = ((int) Math.floor(xSide * ySide)) * plantsPerSquareMeter;
totalCost = totalPlants * plantCost;

System.out.println("You need to plant " + totalPlants + " plants to fill up a " + xSide + " by " + ySide + " field.");
System.out.println("At \$" + (double)plantCost/100 + " per plant the cost will be: \$" + (double)totalCost/100);
}
}
``````

I’m not certain if I’ve used the right variable types (int, double) for the values. They work for this exercise, but I’m not sure if I could have picked better types for future changes. If you’re a programmer, perhaps you could correct me?

So that’s my first week. I’m nervous, but looking forward to my next lesson. I’ll be a javacoderhacker soon!

Update: 2009-08-03

I’ve taken another look at the code and rewritten it to use `int` for all the money transactions. I’ve also used `Math.floor` on the (now `double`) field dimensions to account for sizes other than whole meters, to get the maximum number of plants into the field[^2] . Any better? Is it ok to leave the values as `int` and print as `double`? I can’t get the printed costs to round to two decimal places. A few suggestions I found look like overkill.

1. which of course only shows them if I actually CAN do it [^2]: of course this neglects the fact you could put less than five plants into a partial square meter, but this is getting ridiculous already ↩︎

Javahackercoding 2: This time, it's personal

Last night was a wash Java wise. I’ll be writing another post soon, once I’ve gone through my text book1 , and dissecting what we covered last night. Until I do that, I’m completely lost. And not because I can’t understand it so much as the delivery was all over the place.

My lecturer complained a couple of times that the text and notes go into complicated areas that if he were to teach it, would not be covered yet — which is fair enough. But then time and again he himself would veer off into areas that I’m sure will be covered in a few weeks (ie. not now) and just makes things more confusing now.

And what is with using “Dog” as an example of a program? Every introduction to programming I’ve read uses dogs, cats, cars and pizza to explain classes. That’s useful for about as long as it takes for you to “get” that a class can have attributes and functions, but beyond that is completely meaningless in a practical sense. Using dogs for coding examples just makes my brain hurt, because I can’t see how you can perform arithmetic on a dog, or use a dog to perform a function for another dog. I get that it’s using simple things to explain new concepts, but to me it just clouds the issue. Give me a real example (a simple one) of how making a function and calling it generates a result, and I’ll be happy. Unless your example is `int x = a+b;` - that’s almost as meaningless as Dog().

I apologise if I’ve used the incorrect terms for things in the previous paragraph. I also stress that I can’t do better or think of more useful examples because I still can’t program yet. But I’m working on it. And I’m gonna' read a chapter ahead this time, as I suspect my classmates are only ahead of me by a hair as I’m pretty sure all the questions they were asking would have been straight forward and obvious if they were reading the text (judging by the questions they asked about stuff even I knew).

Please correct me or share your thoughts about how Dog() is actually a useful thing to learn!

1. yes I have it now! ↩︎

Javahackercoding 3: With a Vengeance

This week has been mad. Both my girls have had colds and one has been teething1 , so finding time to study between looking after them (and myself to make sure I don’t get it too) has been difficult. I’ve read my chapters, but I’m not one ahead like I wanted to be. And I’ve only done two of the five exercises for this chapter. It’s my first real OO introduction too. Until now I’ve understood “int”, “double” etc. but now we’re getting in to what has been behind the veil for me when I’ve tried to program before - how you create classes, and call them from other classes.

So I’ve built my Rectangle class and it looks like this:

``````public class Rectangle {
private double length;
private double width;
private double area;
private double perimeter;

public Rectangle(){
this.length = 1.0;
this.width = 1.0;
}

public Rectangle(double theLength, double theWidth){
length = theLength;
width = theWidth;
}

public double getArea() {
area = width * length;
return area;
}

public double getPerimeter(){
perimeter = (width * 2) + (length * 2);
return perimeter;
}
}
``````

Now feel free at this point to tell me where if I’ve gone wrong there. At line 12-14 the book tells me to do `this.length = length;` and so on, but I wanted to try it the other way here just to wrap my head around what was happening. So that’s all well and good and we go on to make a test class, RectangleTest:

``````public class RectangleTest {

public static void main(String[] args) {
Rectangle small = new Rectangle(2.0,3.0);
Rectangle noArgs = new Rectangle();
Rectangle large = new Rectangle(20.4,30.6);
Rectangle notDouble = new Rectangle(4,6);
Rectangle stupid = new Rectangle(3.2,400.1);

System.out.println("Small rectangle: A=" + small.getArea() + "
P="+small.getPerimeter());
System.out.println("Default rectangle: A=" + noArgs.getArea() + "
P="+noArgs.getPerimeter());
System.out.println("Large rectangle: A=" + large.getArea() + "
P="+large.getPerimeter());
System.out.println("Rectangle not written as double: A=" +
notDouble.getArea() + " P="+notDouble.getPerimeter());
System.out.println("Stupidly proportioned rectangle: A=" +
stupid.getArea() + " P="+stupid.getPerimeter());
}
}
``````

Now that seems fine to me too. Maybe you can point out something I’ve missed, because when I run the thing (which works exactly as I’d planned btw) I get this output from NetBeans:

``````Small rectangle: A=6.0 P=10.0
Default rectangle: A=1.0 P=4.0
Large rectangle: A=624.24 P=102.0
Rectangle not written as double: A=24.0 P=20.0
Stupidly proportioned rectangle: A=1280.3200000000002 P=806.6
BUILD SUCCESSFUL (total time: 0 seconds)
``````

Can you spot the weirdness? Why would the Area be returned as “1280.3200000000002”? I added a method to just display the area alone2, and it’s definitely being calculated as 1280.3200000000002, which is just strange, and I want to know if it’s something I’ve done incorrectly, or a quirk of Java/NetBeans.

So that’s where I am. I’m gonna' read up on the next chapter before class tonight. And if I get time, I’ll do some more of the exercises too. So if I’m not on the right track, please tell me before I go to far!

1. I’ll let you guess which ↩︎

2. `public void displayArea() {System.out.println(getArea());}` ↩︎

setJavahackercoding(3.1)

I managed to code me up some of the exercises from chapter 4, and I’m all over classes. The final exercise was to create a Robot class that took a name, weight, bad habit(?), artificial intelligence level, and whether it could see. As an extension exercise, it could also have a “memory module” that allowed 5 mutations (changes) to either the bad habit, or the AI.

My Robot.java class is below:

``````public class Robot {
private String name;
private double weight;
private boolean hasVision;
private int aiq;
private int mutations;
private boolean decommissioned;

public Robot(String name, double weight, String badHabit, boolean
hasVision, int aiq){
this.name = name;
if (weight &lt; 0){
this.weight = Math.abs(weight);
}
else {
this.weight = weight;
}
this.hasVision = hasVision;
this.aiq = aiq;
if (this.aiq &lt;= 0){
this.aiq = 0;
}
if (this.aiq &gt;= 3){
this.aiq = 3;
}
mutations = 0;
decommissioned = false;
}

public void mutate(){
mutations++;
if (mutations &gt;= 5){
decommissioned = true;
}
}

if (!decommissioned){
mutate();
}
}

if (!decommissioned){
if (aiq &lt; 3){
aiq++;
}
else {
aiq = 3;
}
mutate();
}
}

public String getName(){
return name;
}

public double getWeight(){
return weight;
}

public boolean getSight(){
return hasVision;
}

public String getAIQ(){
if (aiq 0){ return "Non Existant"; } if (aiq 1){
return "Low";
}
if (aiq == 2){
return "Medium";
}
else {
return "High";
}
}

}

public void displayDetails(){
System.out.println("The robot's name is " + name);
System.out.println("The robot's weight is " + weight);
System.out.println("The robot can see = " + hasVision);
System.out.println("The robot's AIQ is " + getAIQ());
System.out.println("The robot has undergone " + mutations + "
mutations.");
System.out.println();
}
}
``````

It’s long. It’s also full of stuff I didn’t end up using in the test class, as I hate typing out `System.out.println();` over and over to test stuff, so I included the outputs in a displayDetails() method. Probably should add those as tests at least once, just to check my syntax, but that would make my test even longer. This is my RobotTest.java class:

``````public class RobotTest {
public static void main(String[] args) {
Robot robby = new Robot("Robby",104,"Smoking",false,1);
Robot bender = new Robot("Bender",200,"Drinking",true,2);
Robot vacuum = new Robot("Vacuulux",20,"Sucking",false,-1);
Robot astro = new Robot("Toby",-80,"Playing too much",true,3);

robby.displayDetails();
robby.displayDetails();

bender.displayDetails();

vacuum.displayDetails();
vacuum.displayDetails();

astro.displayDetails();
astro.displayDetails();
}
}
``````

The test helped me to pick up that my coding was wrong in my Robot. Originally I had omitted line 20, and had the test on line 21 as `if (aiq < = 0){this.aiq = 0;} if (aiq >= 3){this.aiq = 3;} else {this.aiq=aiq;}`. I’m not sure why this doesn’t work – if AIQ is less than zero it still sets this.aiq to the retrieved value – but I presume the test cannot read `aiq` unless it has been retrieved and put into `this.aiq`. Its seems better to do it this way anyway, as it’s less typing and less ambiguous. But that’s something I can say I’ve learned.

As for my `double` trouble this morning, I’ve been reading up on why one of my values had some extra decimals, and I believe it’s a particular problem when you try and store 0.1 in a double. I still have no idea how to get around it though and it seems like Java should be able to handle something like that, but who am I to judge, with my Tomatoes.java and my RobotTest.java.

So on to class tonight!

Update: I’m sitting in class. Looking over an example from the lecturer, I’ve realised that my original code didn’t work because I missed `else if`. I added it, and the code I originally thought should work worked!

The big 4 oh (javahackercoding)

So I have neglectfully not blogged since my update during class last week. All week I was thinking I had already. When my mum1 said she’d read my site and hoped class would get better for me I realised the impression I had left you with was still that I had no idea what was going on, and it was all over my head.

Thankfully that is not the case! Last week I discovered that I’m right on track, I’m keeping pace with my class, and I’m thoroughly enjoying myself. Working through some problems on Monday and Tuesday night was a blast, and I’m really enjoying what I’m learning. That said I hit a roadblock when the final problem asked me to create a sort of menu system for creating and updating the details of housing units. In class last week we covered if statements, and this week loops, so I don’t feel at all bad about leaving the problem till this week, as I’m pretty sure the best way to handle the menus is with loops.

On the other hand, I’m not certain the best way to structure things. I could whack the whole code into the main method, and play it like a batch file, or I could fumble about a bit and try breaking the code into classes/methods and seeing how that goes. One way I know will work, the other is the right way… So I’ve put it off for homework this week and hopefully I’ll get enough into my head tonight to help push me the right way.

So no code examples this week. I suppose I could chuck something in here, but they’re all getting mighty long (and who’s reading it really?), even to do the simplest tasks.

Thank you everyone who’s been commenting and answering my silly questions. It’s all really helpful, and makes me feel like I’m becoming a part of the programming community!

1. hello mum! ↩︎

Quick update before javahackercoding 6 (so this is 5?)

Quickie:

• Last class was useless, as I forgot my USB with my current work on it so I couldn’t actually use the time to keep working on my assignment.

• I got the assignment written and handed up, but I wasn’t happy with it. I have the control stuff sorted (if, while), but not the OO-ness of Java.

• The assignment code felt bulky and wrong, and I need to split it into separate classes/methods, but just cant figure it out.

• My text still hasn’t arrived and I’m using the 2002 version. It’s out of date and the exercises are absolutely brimming over with wrongability

• There is something weird about fully understanding every example you attempt to write, and knowing exactly what the lecturer is talking about, and reading all the chapters you are supposed to, and still finding that the assignment you have to submit in a week is beyond what you know you know. It feels like the assignment was stuck into the flow of the course prematurely.

That is all. If you are a Javahackercoder and you are reading this, and you can spare a bit of your time to help explain a few things to me about making decisions about which parts of my code to create objects/methods from, I’d be eternally grateful1 .

1. Conditions apply, gratitude not guaranteed to extend for eternity ↩︎

60 GOTO JAVAHACKERCODING

It’s 9:30, so class just finished, but I left at 8. Another night of confusing information that would probably make sense if I’d read the text before hand, or wasn’t being taught by someone who’s thinking of examples on the fly and can’t finish a sentence before moving on to another concept.

I’m gonna just sit down tomorrow and current text be damned, read a whole bunch of chapters and just work on the half assed examples in the text I have. Hopefully that will keep me going. I can’t keep putting it off.

My next chapter is Methods, so hopefully that might answer some of my questions about when to use methods and how.

private int javaHackerCoding = 7;

I may have skipped one there I think. Class was good this last week. I had a look at the example code we were given for the last hand up I did, and used it to properly break my long code into methods.

I don’t think I’ve quite reached that “click” moment that people say will come, but it was nice to finally get that a class can be handled in the same way as the less complex data types, ie you can pass a class to a method, and assign place-holder classes like you can with any `int` or `String`. So you have something like this:

``````private static Unit rentUnit(){
Unit unitToRent = unit1;
return unitToRent;
}
``````

Which should be obvious, but I didn’t get it until this week. So that was my big moment, and I wasn’t sure it had sunk in, but then I began the first part of our major assignment, and knew I’d got it when I was setting up my constructors and throwing classes around like they were any old `boolean`

So yay for me! I’m actually finding the first part of this assignment too easy, and would have liked it a bit harder so I could properly test myself. But I’ll take it easy and learn it slowly so I get it properly. I really want to do this right the first time.

Javahackercoding ∞

I lost track of what week we’re up to, and I’ve got a few updates to roll into this one, so my titles are off.

Had a major assignment and a test since last time I updated, so I thought it might be time to report how they went.

I was happy with my assignment and my grade of Satisfactory, until I realised I could have gotten Outstanding! Apparently my only mistake was to not:

Keep the instance variable on the same line as its label.

Eg in my toString class I put:

``````public String toString() {
return super.toString() +
" Place: " +
place +
"; State: " +
state +
"; Postcode: " +
postcode +
"; Country: " +
country;
}
``````

``````public String toString() {
return super.toString() +
" Place: " + place +
"; State: " + state +
"; Postcode: " + postcode +
"; Country: " + country;
}
``````

Obvious, but worth marking me down? Maybe I did something else wrong, but I don’t think so.

I also attempted the test which included a section on Arrays. I haven’t done any study on arrays. I was worried. But the test was open book, so I learned what I needed as I went, and even had time to attempt the merit. My result?

So I’m pretty happy with that.

Now on to Polymorphism and Interfaces!