PDA

View Full Version : Java_noob_assigmnent



Sir R. M8gic1an
10-02-2009, 12:38 AM
Hey guys, first assignment at uni. Anyone mind checking it over?



public class CodeMate1Java
{
public static final double
SWEETENER_TO_KILL_MOUSE = 0.5,
MOUSE_WEIGHT = 3.0,
PERSON_START_WEIGHT = 80.0,
PERSON_DESIRED_WEIGHT = 65.0,
SWEET_PERCENTAGE_IN_CAN = 0.001,
LIQUID_QUANTITY_IN_CAN = 0.33; //liters

double sweetenerToWeightDeadlyRatio, personMaximumSweetenerToIngest;

public static void main(String[] args)
{
sweetenerToWeightDeadlyRatio = SWEETENER_TO_KILL_MOUSE / MOUSE_WEIGHT;
personMaximumSweetenerToIngest = PERSON_DESIRED_WEIGHT * sweetenertoWeightDeadlyRatio;

//According to physics 1 kg = 1.04 L, we'll just use a 1 to 1 ratio
System.out.println("The person can not drink more than " +
(personMaximumSweetenerToIngest/(LIQUID_QUANTITY_IN_CAN*SWEET_PERCENTAGE_IN_CAN))
+ " cans safely");
}

}





public class CodeMate2Java
{
public static final boolean LOVE = True;

public static void main(String[] args)
{
if (LOVE) {
System.out.println("I love you.");
} else {
System.out.prinln("I hate you.");
}
}
}



Cheers,

~RM

senrath
10-02-2009, 12:45 AM
Slight error in your first piece of code. You can't reference a non-static field from within a static field. Meaning that you can either make sweetenerToWeightDeadlyRatio and personMaximumSweetenerToIngest static, or you have to create a new CodeMate1Java object within the main code, like this:
public class CodeMate1Java
{
public static final double
SWEETENER_TO_KILL_MOUSE = 0.5,
MOUSE_WEIGHT = 3.0,
PERSON_START_WEIGHT = 80.0,
PERSON_DESIRED_WEIGHT = 65.0,
SWEET_PERCENTAGE_IN_CAN = 0.001,
LIQUID_QUANTITY_IN_CAN = 0.33; //liters

double sweetenerToWeightDeadlyRatio, personMaximumSweetenerToIngest;

public static void main(String[] args)
{
CodeMate1Java myCode = new CodeMate1Java();
myCode .sweetenerToWeightDeadlyRatio = SWEETENER_TO_KILL_MOUSE / MOUSE_WEIGHT;
myCode .personMaximumSweetenerToIngest = PERSON_DESIRED_WEIGHT * myCode .sweetenerToWeightDeadlyRatio;

//According to physics 1 kg = 1.04 L, we'll just use a 1 to 1 ratio
System.out.println("The person can not drink more than " +
(myCode .personMaximumSweetenerToIngest/(LIQUID_QUANTITY_IN_CAN*SWEET_PERCENTAGE_IN_CAN))
+ " cans safely");
}

}
Also, you have a typo when assigning the value of personMaximumSweetenerToIngest. You have it as sweetenertoWeightDeadlyRatio when it should be sweetenerToWeightDeadlyRatio.

Sir R. M8gic1an
10-02-2009, 12:48 AM
Thanks, fixed. (not on the post tho)

~RM

Nadeem
10-02-2009, 12:52 AM
1. you forgot to declare a static pointer for your second set of doubles.
2. i think you forgot java is case-sensitive (sweetenertoWeightDeadlyRatio -> sweetenerToWeightDeadlyRatio).
3. its supposed to be good practice to practice to initiate the variables before you use them.

i guess here is your example with the listed points:


public class CodeMate1Java
{
public static final double
SWEETENER_TO_KILL_MOUSE = 0.5,
MOUSE_WEIGHT = 3.0,
PERSON_START_WEIGHT = 80.0,
PERSON_DESIRED_WEIGHT = 65.0,
SWEET_PERCENTAGE_IN_CAN = 0.001,
LIQUID_QUANTITY_IN_CAN = 0.33; //liters

static double sweetenerToWeightDeadlyRatio = 0d, personMaximumSweetenerToIngest = 0d;

public static void main(String[] args)
{
sweetenerToWeightDeadlyRatio = SWEETENER_TO_KILL_MOUSE / MOUSE_WEIGHT;
personMaximumSweetenerToIngest = PERSON_DESIRED_WEIGHT * sweetenerToWeightDeadlyRatio;

//According to physics 1 kg = 1.04 L, we'll just use a 1 to 1 ratio
System.out.println("The person can not drink more than " +
(personMaximumSweetenerToIngest/(LIQUID_QUANTITY_IN_CAN*SWEET_PERCENTAGE_IN_CAN))
+ " cans safely");
}
}


for the 2nd example you can do the following to be more impressive (:


public class CodeMate2Java
{
public static final boolean LOVE = True;

public static void main(String[] args)
{
System.out.println(LOVE ? "I love you" : "I hate you.");
}
}


Edit: ninja'd by senrath >.<



~NS

Sir R. M8gic1an
10-02-2009, 12:58 AM
humm. = 0d ? why the d? for the second one i understand it from php :p

~RM

Nadeem
10-02-2009, 01:02 AM
humm. = 0d ? why the d? for the second one i understand it from php :p

~RM

d = abbrv for double, so its like the same thing as 0.0.
you can also have:
f = float

(:



~NS

senrath
10-02-2009, 01:03 AM
humm. = 0d ? why the d? for the second one i understand it from php :p

~RM

It tells the system that it's a double value, rather than an integer.

Edit: Now I'M the one ninja'd. Curse you!

Wizzup?
10-02-2009, 02:24 AM
Next time use [ highlight=java ] ?

Simtoon
10-02-2009, 04:43 AM
Your Assignment, Havent you done "All My Own Work?" or maybe thats why Sydney, NSW

Method
10-02-2009, 05:34 AM
Why are your variable names so long? Also, why are the constants public when no other class uses them? A private modifier or no access modifier at all would be better. The other two double fields you have probably should just be local variables as well.

Nadeem
10-02-2009, 06:24 AM
btw what uni are you at? i was thinking uni first assignment would be much hardocre then that! my grade 12 first assignment was much more length :p

::

/*
* Program: Bank Manager
* Author: Nadeem Syed
* Date: Sept. 25, 2009
*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class BankManager extends Applet implements ActionListener
{
//* State global variables
final static Boolean DebugMode = true;
private int[] intAmountArr = new int[2];
private int[][] intBillsArr = new int[11][2];
private Image[] imgBillsArr = new Image[11];
private TextField txfWithdraw = new TextField(10);
private Button btnWithdraw = new Button("Withdraw");
private Button btnReset = new Button("Reset");
private Label strError = new Label("", Label.CENTER);

public void init()
{
PrintLine("~BEGIN~", true, true, true);

// Set layout null
setLayout(null);

// Add the title
Label lblTitle = new Label("Enter Amount");
add(lblTitle);
lblTitle.setBackground(new Color(160, 0, 0));
lblTitle.setForeground(Color.white);
lblTitle.setFont(new Font("TimesRoman", Font.PLAIN, 19));
lblTitle.setBounds(50, 5, 120, 30);

// Add the textfield
add(txfWithdraw);
txfWithdraw.setBounds(170, 9, 100, 20);
txfWithdraw.addActionListener(this);

// Add the buttons
add(btnWithdraw);
btnWithdraw.setBounds(280, 7, 70, 25);
btnWithdraw.addActionListener(this);

add(btnReset);
btnReset.setBounds(325, 270, 70, 25);
btnReset.addActionListener(this);

// Load images
for (int i = 0; i <= 10; i++)
imgBillsArr[i] = getImage(getCodeBase(), "images/" + (i>6 ? "c" : "d") + (i+1) + ".jpg");

this.LoadBills();
}

//* ObtainValues(): Obtain and insert amount withdrawn into array
// @param String amount: The amount entered by user to withdraw
private void ObtainValues(String amount)
{
PrintLine("[ObtainValues] @amount: " + amount, true, true, true);

try
{
// Check if @amount starts with '$', if false, print error
if (!amount.startsWith("$")) strError.setText("Please enter the dollar sign. ($)");

// Create a regex compilation based on pattern
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[$.\\s]");

// Split amount using the pattern above
String[] arr = p.split(amount);

// Adds '1' incase of array [0] being blank
int push = arr[0].equals("") ? 1 : 0;

// Add leading zeroes to the cents
if (arr[push + 1].length() < 2) arr[push + 1] += "00";

// Check if number of cents is greater than 2 digits, if true, trim it
if (arr[push + 1].length() > 2) arr[push + 1] = arr[push + 1].substring(0, 2);

// Store values into our array
intAmountArr[0] = Integer.parseInt(arr[push]);
intAmountArr[1] = Integer.parseInt(arr[push + 1]);

// Check if numbers are positive, if negative, throw new Exception()
if (intAmountArr[0] < 0 || intAmountArr[1] < 0) throw new Exception();

PrintLine("Dollars: " + intAmountArr[0] + ", Cents: " + intAmountArr[1], true, true, true);
}
catch(Exception e)
{
strError.setText("Please enter a proper format. ($##.##)");
}
}

//* LoadBills(): Loads the array with values of the bills
private void LoadBills()
{
// Assign dollar and cent amounts to the 2D array
// Dolars: [0] = 1, [1] = 2, [2] = 5, [3] = 10, [4] = 20, [5] = 50, [6] = 100
// Cents: [7] = 1, [8] = 5, [9] = 10, [10] = 25
for (int i = 0; i <= 10; i++)
{
intBillsArr[i][0] = i==2 || i==8 ? 5 : (i==3 || i==9 ? 10 :
(i==4 ? 20 : (i==5 ? 50 : (i==6 ? 100 : (i==10 ? 25 : (i==7 ? 1 : i+1))))));
PrintLine((i>0 ? ", " : "") + intBillsArr[i][0], i==10, true, i==0);
}
}

//* SetChange(): Sets the amount of change given
private void SetChange()
{
// Local variables to hold looping value of the amount left
int c = intAmountArr[1], d = intAmountArr[0];

// Loop through and assign change to each array of bills
for (int i = 10; i >= 0; i--)
{
intBillsArr[i][1] = (int)(i > 6 ? c : d) / intBillsArr[i][0];
if (i > 6) c -= intBillsArr[i][1] * intBillsArr[i][0];
else d -= intBillsArr[i][1] * intBillsArr[i][0];
PrintLine(String.format("i[%d] | %s%d: %d | c/d: %d", i, (i>6) ? "¢" : "$",
intBillsArr[i][0], intBillsArr[i][1], (i>6) ? c : d), true, true, true);
}
}

//* PrintLine(String output, Boolean newLine, Boolean debug): Writes into the console
// @param String output: The text to output in the Console
// @param Boolean newLine: Adds a break for new line if true
// @param Boolean debug: If true, then prints in DEBUG mode
static void PrintLine(String output, Boolean newLine, Boolean debug, Boolean sayDebug)
{
if (debug && !DebugMode) return;
System.out.print((debug && sayDebug ? "[DEBUG]: " : "") + output + (newLine ? "\n" : ""));
}

//* actionPerformed(ActionEvent e): Execute upon user action
public void actionPerformed(ActionEvent e)
{
// Execute withdrawal if the user clicked the Withdraw button
if (e.getSource() == btnWithdraw)
{
String amount = txfWithdraw.getText().trim();
PrintLine("[BankManager] @amount: " + amount, true, true, true);
this.strError.setText("");
this.remove(this.strError);
this.ObtainValues(amount);
this.SetChange();
if (!this.strError.getText().equals("")) this.add(this.strError);
repaint();
}

if (e.getSource() == btnReset)
{
this.strError.setText("");
this.remove(this.strError);
this.ObtainValues("$0.001");
this.SetChange();
if (!this.strError.getText().equals("")) this.add(this.strError);
repaint();
}
}

//* paint(Graphics g): Paint onto the canvas
public void paint(Graphics g)
{
// Create the 2 rectangles in the background
g.setColor(new Color(160, 0, 0));
g.drawRect(0, 0, 399, 299);
g.fillRect(0, 0, 399, 39);

// Check and display error
if (!this.strError.getText().equals(""))
{
this.strError.setBackground(new Color(255, 99, 99));
this.strError.setForeground(Color.white);
this.strError.setBounds(26, 71, 349, 124);
this.strError.setFont(new Font("TimesRoman", Font.PLAIN, 19));
g.setColor(new Color(160, 0, 0));
g.drawRect(25, 70, 350, 125);
return;
}

// Draw the images for the bills, and all the text beneath the images
for (int i = 0; i <= 10; i++)
{
Point p = new Point(((i>1 && i<7 ? 46 : 56) * (i-(i>6 ? 7 : 0))) + (i>1 && i<7 ? 65 : 20), 60 + (i>6 ? 130 : 0));
g.setColor((i+1) % 2 == 0 ? new Color(219, 219, 219) : new Color(243, 243, 243));
g.fillRect(p.x - (i>1 && i<7 ? 5 : 3), p.y + 50, i>2 && i<7 ? 46 : 56, i>6 ? 55 : 65);
g.setColor((i+1) % 2 == 0 ? new Color(200, 200, 200) : new Color(233, 233, 233));
g.fillRect(p.x - (i>1 && i<7 ? 5 : 3), p.y + 50, i>2 && i<7 ? 46 : 56, i>6 ? 35 : 45);
g.drawImage(imgBillsArr[i], p.x, p.y, this);
g.setColor((i+1) % 2 == 0 ? Color.black : Color.gray);
g.drawString("" + intBillsArr[i][1], p.x + (i>1 && i<7 ? 15 : 20), p.y + (i>6 ? 80 : 90));
g.drawString((i>6 ? "¢" : "$") + (intBillsArr[i][1] * intBillsArr[i][0]), p.x + 3, p.y + (i>6 ? 99 : 109));
}
}
}


(: Well it wasn't this hardcore but for sure was the shortest code in the class, the others did like 300+ lines



~NS

Method
10-02-2009, 10:04 AM
blah

There's no way an introductory course to Java would have that as the first assignment, even if it is a university course.

Nava2
10-02-2009, 10:19 AM
My first assignment:

public void drawRectangle(int width, int height)
{
double initHeading = this.getHeading(); // Get the initial heading to reset later
boolean initPenState = this.isPenDown(); // and whether the pen is up or down

if (!initPenState)
{
this.penDown();
}

this.setHeading(90);
this.forward(width);
this.turnRight();
this.forward(height);
this.turnRight();
this.forward(width);
this.turnRight();
this.forward(height);

this.setHeading(initHeading);
this.setPenDown(initPenState);
}

^ I had it done with for loops etc, but my teacher said the concepts were too advanced and I had to dumb it down...

import java.awt.Color;

public class TurtleArt
{
public static void main (String[] args)
{
World mainWorld = new World(); // Create our world and turtle!
Turtle turtle = new Turtle(mainWorld);

turtle.setPenWidth(3); // Set our pen width, outside must be 3
turtle.penUp(); // Lift the pen so our turtle doesn't create an unnecessary path

turtle.moveTo(5, 5);
turtle.setPenColor(Color.BLACK);

turtle.drawRectangle(mainWorld.getWidth() - 10, mainWorld.getHeight() - 10);

turtle.setPenColor(Color.RED);
turtle.setPenWidth(5);

// Draw the required rectangles at their positions
turtle.moveTo(50, 50);
turtle.drawRectangle(150, 400);

turtle.moveTo(600, 150);
turtle.drawRectangle(-300, 200);

// Hide our turtle for aesthetics!
turtle.hide();
}
}

It moves a turtle around the screen drawing three rectangles. Stupid easy.

Also, the if statement was almost wrong, we still don't know them after a month of classes.. nor do we know for loops.. switch statements.. all things I learned from the interwebz.

senrath
10-02-2009, 10:30 AM
There's no way an introductory course to Java would have that as the first assignment, even if it is a university course.

It's quite possible. Intro to INSERT PROGRAMMING LANGUAGE HERE classes in College/University are usually really, really simple to start out.

Method
10-02-2009, 10:54 AM
It's quite possible. Intro to INSERT PROGRAMMING LANGUAGE HERE classes in College/University are usually really, really simple to start out.

Nadeem's program isn't "really, really simple" for someone who has no idea how to program in Java (and would be even harder to create for someone who didn't know any programming languages).

senrath
10-02-2009, 10:56 AM
Nadeem's program isn't "really, really simple" for someone who has no idea how to program in Java (and would be even harder to create for someone who didn't know any programming languages).

Oh, I thought you were referring to RM's. No, Nadeem's wouldn't be the first assignment in an into course.

Nadeem
10-02-2009, 11:29 AM
Ooooh no no no lol this wasn't a intro assignment, i didn't know RM was in at intro my bad :p

lol Nava2, i feel u bro :p I dun even know what my intro assignment were (except for first day, it was if-else-loops), i skipped them all cuz they were too simple and i was impatient and if i went to class (fist day) i'd just end up helping the teacher teach...Its sad, teaching yourself is the best way if u wanna be a unique programmer i guess, school is just good for the credits



~NS

Nava2
10-02-2009, 11:58 AM
@Nadeem, I do that, I read the lecture summaries, then read tuts online.

Way easier than sitting bored in a lecture.

Its actually ridiculous.

tls
10-02-2009, 12:01 PM
@Nadeem, I do that, I read the lecture summaries, then read tuts online.

Way easier than sitting bored in a lecture.

Its actually ridiculous.

What's your major?

Sir R. M8gic1an
10-02-2009, 04:31 PM
@Nadeem, I do that, I read the lecture summaries, then read tuts online.

Way easier than sitting bored in a lecture.

Its actually ridiculous.

Lucky you guys, i actully need a 70% attendancy rate :(

~RM

Wizzup?
10-02-2009, 07:35 PM
There's no way an introductory course to Java would have that as the first assignment, even if it is a university course.

I quite agree. I've been assisting in courses with students who have just started programming at the University (Computer Science study), and they have no knowledge of programming when they start. (Obviously)

Example: (One exercise per week.)

The first exercise consists of writing your own factorial function.
The second one consists of basic input with the Scanner class, and some simple mathematical functions.
The third one exists out of generating Lucas sequences.
The fourth exercise is a Palindrome tester.

The exercise Nadeem claims to be his first exercise at the University is way to hard for any starter. :p

Edit third -> fourth. :o

Bobarkinator
10-02-2009, 08:04 PM
I quite agree. I've been assisting in courses with students who have just started programming at the University (Computer Science study), and they have no knowledge of programming when they start. (Obviously)

Example: (One exercise per week.)

The first exercise consists of writing your own factorial function.
The second one consists of basic input with the Scanner class, and some simple mathematical functions.
The third one exists out of generating Lucas sequences.
The third exercise is a Palindrome tester.

The exercise Nadeem claims to be his first exercise at the University is way to hard for any starter. :p

I just made a palindrome tester yesterday in Java good times.

Nadeem
10-02-2009, 08:10 PM
lol Wizzup? i said its my first ACTUAL assignment, i dunno bout the other ones before, and in addition, it wasn't supposed to be as complex as mine, no one in my class even know what the ? : operators do, i just used those cuz i was too lazy to do it the long way like all the others did.

ex:

Point p = new Point(((i>1 && i<7 ? 46 : 56) * (i-(i>6 ? 7 : 0))) + (i>1 && i<7 ? 65 : 20), 60 + (i>6 ? 130 : 0));


Everyone else had a repetitive series of drawstrings and drawimages and draw/fill rectangles (tell me thats not ugly :p) btw im not in uni yet, last year highschool^^

Edit: I expected uni classes to be more complex thinking you need some sort of computer science credit(s) to take that class and most likely would've done some if not very simple java.



~NS

Wizzup?
10-02-2009, 08:24 PM
lol Wizzup? i said its my first ACTUAL assignment, i dunno bout the other ones before, and in addition, it wasn't supposed to be as complex as mine, no one in my class even know what the ? : operators do, i just used those cuz i was too lazy to do it the long way like all the others did.

ex:

Point p = new Point(((i>1 && i<7 ? 46 : 56) * (i-(i>6 ? 7 : 0))) + (i>1 && i<7 ? 65 : 20), 60 + (i>6 ? 130 : 0));


Everyone else had a repetitive series of drawstrings and drawimages and draw/fill rectangles (tell me thats not ugly :p) btw im not in uni yet, last year highschool^^

Edit: I expected uni classes to be more complex thinking you need some sort of computer science credit(s) to take that class and most likely would've done some if not very simple java.



~NS

Well, I bet their code was more readable than yours in this case. :)
Since we're into writing obfuscated one liners ( ;) ) : (Palindrome tester)



isp = lambda r: (lambda s: map(lambda(x, y): x == y, zip([x for x in s], [s[len(s) - z - 1] for z in range(len(s))])) == map(lambda x: True, range(len(s))))(filter(None, map(lambda(ss, c): ss * (ss >= 'a' and ss <= 'z' and c) + ss * (ss >= '0' and ss <= '9' and not c), zip(r, map(lambda x: sum(map(lambda q: 1 * (q >= 'a' and q <= 'z'), r)) > len(r) / 2, range(len(r)))))))


EDIT: Btw, your java code is poorly commented. // is semi-forbidden in modern java-coding conventions. ;)
EDIT2: Highlight -> quote.

Nava2
10-02-2009, 08:27 PM
What's your major?''

Medical studies


I quite agree. I've been assisting in courses with students who have just started programming at the University (Computer Science study), and they have no knowledge of programming when they start. (Obviously)

Example: (One exercise per week.)

The first exercise consists of writing your own factorial function.
The second one consists of basic input with the Scanner class, and some simple mathematical functions.
The third one exists out of generating Lucas sequences.
The third exercise is a Palindrome tester.

The exercise Nadeem claims to be his first exercise at the University is way to hard for any starter. :p

You are a TA? Also, I can understand that. My textbook just came with these silly turtles that you can put in a world. So we have to create methods etc to play with them.

My course is also a "multi-media approach to programming java"

senrath
10-02-2009, 09:01 PM
EDIT: Btw, your java code is poorly commented. // is semi-forbidden in modern java-coding conventions. ;)
EDIT2: Highlight -> quote.

Huh? Where did you hear that // is semi-forbidden?

Wizzup?
10-02-2009, 11:14 PM
Huh? Where did you hear that // is semi-forbidden?

I did not hear it. It is general knowledge. I think ANSI C even warns (or errors) if coders use //.
Since Java is pretty much based on C when it comes to syntax, one can assume that the same applies. JavaDoc is even stricter.

Try to compile this in C, with the following flags:


int main() {
// this is a comment
return 0;
}



$ gcc test.c -ansi -Wall -pedantic
test.c: In function ‘main’:
test.c:2: error: expected expression before ‘/’ token
test.c:4: warning: control reaches end of non-void function


Furthermore, if one wants others to read his code, it must be well commented.
I think at every university they teach pupils that "//" is simply a no-go, and they must use /* for single line comments too.

For you to compare:


/* In this statement we test b, and if b is true, we give a the value of c. */
if(b)
a = c;


versus

if(b) // In this statement we test b, and if b is true, we give a the value of c.
a = c;


And


/*
* Program: Bank Manager
* Author: Nadeem Syed
* Date: Sept. 25, 2009
*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class BankManager extends Applet implements ActionListener
{
//* State global variables
final static Boolean DebugMode = true;
private int[] intAmountArr = new int[2];
private int[][] intBillsArr = new int[11][2];
private Image[] imgBillsArr = new Image[11];
private TextField txfWithdraw = new TextField(10);
private Button btnWithdraw = new Button("Withdraw");
private Button btnReset = new Button("Reset");
private Label strError = new Label("", Label.CENTER);

public void init()
{
PrintLine("~BEGIN~", true, true, true);

// Set layout null
setLayout(null);

// Add the title
Label lblTitle = new Label("Enter Amount");
add(lblTitle);
lblTitle.setBackground(new Color(160, 0, 0));
lblTitle.setForeground(Color.white);
lblTitle.setFont(new Font("TimesRoman", Font.PLAIN, 19));
lblTitle.setBounds(50, 5, 120, 30);

// Add the textfield
add(txfWithdraw);
txfWithdraw.setBounds(170, 9, 100, 20);
txfWithdraw.addActionListener(this);

// Add the buttons
add(btnWithdraw);
btnWithdraw.setBounds(280, 7, 70, 25);
btnWithdraw.addActionListener(this);

add(btnReset);
btnReset.setBounds(325, 270, 70, 25);
btnReset.addActionListener(this);

// Load images
for (int i = 0; i <= 10; i++)
imgBillsArr[i] = getImage(getCodeBase(), "images/" + (i>6 ? "c" : "d") + (i+1) + ".jpg");

this.LoadBills();
}

//* ObtainValues(): Obtain and insert amount withdrawn into array
// @param String amount: The amount entered by user to withdraw
private void ObtainValues(String amount)
{
PrintLine("[ObtainValues] @amount: " + amount, true, true, true);

try
{
// Check if @amount starts with '$', if false, print error
if (!amount.startsWith("$")) strError.setText("Please enter the dollar sign. ($)");

// Create a regex compilation based on pattern
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[$.\\s]");

// Split amount using the pattern above
String[] arr = p.split(amount);

// Adds '1' incase of array [0] being blank
int push = arr[0].equals("") ? 1 : 0;

// Add leading zeroes to the cents
if (arr[push + 1].length() < 2) arr[push + 1] += "00";

// Check if number of cents is greater than 2 digits, if true, trim it
if (arr[push + 1].length() > 2) arr[push + 1] = arr[push + 1].substring(0, 2);

// Store values into our array
intAmountArr[0] = Integer.parseInt(arr[push]);
intAmountArr[1] = Integer.parseInt(arr[push + 1]);

// Check if numbers are positive, if negative, throw new Exception()
if (intAmountArr[0] < 0 || intAmountArr[1] < 0) throw new Exception();

PrintLine("Dollars: " + intAmountArr[0] + ", Cents: " + intAmountArr[1], true, true, true);
}
catch(Exception e)
{
strError.setText("Please enter a proper format. ($##.##)");
}
}

//* LoadBills(): Loads the array with values of the bills
private void LoadBills()
{
// Assign dollar and cent amounts to the 2D array
// Dolars: [0] = 1, [1] = 2, [2] = 5, [3] = 10, [4] = 20, [5] = 50, [6] = 100
// Cents: [7] = 1, [8] = 5, [9] = 10, [10] = 25
for (int i = 0; i <= 10; i++)
{
intBillsArr[i][0] = i==2 || i==8 ? 5 : (i==3 || i==9 ? 10 :
(i==4 ? 20 : (i==5 ? 50 : (i==6 ? 100 : (i==10 ? 25 : (i==7 ? 1 : i+1))))));
PrintLine((i>0 ? ", " : "") + intBillsArr[i][0], i==10, true, i==0);
}
}

//* SetChange(): Sets the amount of change given
private void SetChange()
{
// Local variables to hold looping value of the amount left
int c = intAmountArr[1], d = intAmountArr[0];

// Loop through and assign change to each array of bills
for (int i = 10; i >= 0; i--)
{
intBillsArr[i][1] = (int)(i > 6 ? c : d) / intBillsArr[i][0];
if (i > 6) c -= intBillsArr[i][1] * intBillsArr[i][0];
else d -= intBillsArr[i][1] * intBillsArr[i][0];
PrintLine(String.format("i[%d] | %s%d: %d | c/d: %d", i, (i>6) ? "¢" : "$",
intBillsArr[i][0], intBillsArr[i][1], (i>6) ? c : d), true, true, true);
}
}

//* PrintLine(String output, Boolean newLine, Boolean debug): Writes into the console
// @param String output: The text to output in the Console
// @param Boolean newLine: Adds a break for new line if true
// @param Boolean debug: If true, then prints in DEBUG mode
static void PrintLine(String output, Boolean newLine, Boolean debug, Boolean sayDebug)
{
if (debug && !DebugMode) return;
System.out.print((debug && sayDebug ? "[DEBUG]: " : "") + output + (newLine ? "\n" : ""));
}

//* actionPerformed(ActionEvent e): Execute upon user action
public void actionPerformed(ActionEvent e)
{
// Execute withdrawal if the user clicked the Withdraw button
if (e.getSource() == btnWithdraw)
{
String amount = txfWithdraw.getText().trim();
PrintLine("[BankManager] @amount: " + amount, true, true, true);
this.strError.setText("");
this.remove(this.strError);
this.ObtainValues(amount);
this.SetChange();
if (!this.strError.getText().equals("")) this.add(this.strError);
repaint();
}

if (e.getSource() == btnReset)
{
this.strError.setText("");
this.remove(this.strError);
this.ObtainValues("$0.001");
this.SetChange();
if (!this.strError.getText().equals("")) this.add(this.strError);
repaint();
}
}

//* paint(Graphics g): Paint onto the canvas
public void paint(Graphics g)
{
// Create the 2 rectangles in the background
g.setColor(new Color(160, 0, 0));
g.drawRect(0, 0, 399, 299);
g.fillRect(0, 0, 399, 39);

// Check and display error
if (!this.strError.getText().equals(""))
{
this.strError.setBackground(new Color(255, 99, 99));
this.strError.setForeground(Color.white);
this.strError.setBounds(26, 71, 349, 124);
this.strError.setFont(new Font("TimesRoman", Font.PLAIN, 19));
g.setColor(new Color(160, 0, 0));
g.drawRect(25, 70, 350, 125);
return;
}

// Draw the images for the bills, and all the text beneath the images
for (int i = 0; i <= 10; i++)
{
Point p = new Point(((i>1 && i<7 ? 46 : 56) * (i-(i>6 ? 7 : 0))) + (i>1 && i<7 ? 65 : 20), 60 + (i>6 ? 130 : 0));
g.setColor((i+1) % 2 == 0 ? new Color(219, 219, 219) : new Color(243, 243, 243));
g.fillRect(p.x - (i>1 && i<7 ? 5 : 3), p.y + 50, i>2 && i<7 ? 46 : 56, i>6 ? 55 : 65);
g.setColor((i+1) % 2 == 0 ? new Color(200, 200, 200) : new Color(233, 233, 233));
g.fillRect(p.x - (i>1 && i<7 ? 5 : 3), p.y + 50, i>2 && i<7 ? 46 : 56, i>6 ? 35 : 45);
g.drawImage(imgBillsArr[i], p.x, p.y, this);
g.setColor((i+1) % 2 == 0 ? Color.black : Color.gray);
g.drawString("" + intBillsArr[i][1], p.x + (i>1 && i<7 ? 15 : 20), p.y + (i>6 ? 80 : 90));
g.drawString((i>6 ? "¢" : "$") + (intBillsArr[i][1] * intBillsArr[i][0]), p.x + 3, p.y + (i>6 ? 99 : 109));
}
}
}


vs

package Sudoku;

public class BitClass {
protected long[] b;
protected long bits;
protected long bitsSet;
protected long bitMask;



/*
* Creates a BitClass with the given amount of bits.
*/
public BitClass(long amountOfBits) {
b = new long[(int) Math.ceil((double)(amountOfBits / 64.0d))];
bits = amountOfBits;
bitMask = this.computeNumMask();
}

/*
* Creates a copy of the current BitClass
*/
public BitClass copy() {
BitClass bC = new BitClass(0);
bC.bits = this.bits;
bC.b = this.b.clone();
bC.bitsSet = this.bitsSet;
bC.bitMask = this.bitMask;
return bC;
}

/*
* Returns the length of b.
*/
public long length() {
return b.length;
}

/*
* Returns a mask used to compute the number of bits set.
* If the number of bits would be 9, it returns 0x0000 0000 0000 01FF
* This mask is used to drop off the bits that are not used in the last long
* in the array. Because of operations like NOT, the bits in the last long
* of the array might not be 0, therefor they need to be dropped.
* 0xFFFFFFFFFFFFFFFF & 0x0000 0000 0000 01FF leaves only the first 9 bits
* intact.
*/
public long computeNumMask() {
final long bitsMod64 = bits % 64;
long mask = 0;
for(int i = 0; i < bitsMod64; i += 2)
mask |= 3 << i;
return mask >> (bits & 0x1);
}

/*
* Returns the value of the bit at position pos.
*/
public long get(int pos) {
if ((pos < 0) || (pos > b.length)) {
/* Throw Exception */
}
return (b[pos / 64] >> (pos % 64)) & 1;
}

/*
* Set's the value of the bit at position pos to 1.
*/
public void set(int pos) {
if ((pos < 0) || (pos > bits)) {
/* Throw Exception */
}

/* If the bit is set to 0, increase bitsSet and set the bit to 1 */
if((b[pos / 64] >> (pos % 64) & 1) == 0) {
b[pos / 64] |= (1 << pos);
bitsSet++;
}
}

/*
* Set's the value of the bit at position pos to 0.
*/
public void unset(int pos) {
if ((pos < 0) || (pos > bits)) {
/* Throw Exception */
}

/* If the bit is set to 1, increase bitsSet and set the bit to 0 */
if((b[pos / 64] >> (pos % 64) & 1) == 1) {
b[pos / 64] &= ~(1 << pos);
bitsSet--;
}

}

/*
* Performs a not operation on the current BitClass.
*/
public BitClass not() {
BitClass resBitClass = new BitClass(bits);
for(int i = 0; i < this.b.length; i++)
resBitClass.b[i] = ~this.b[i];
resBitClass.bitsSet = resBitClass.countBitsSet();
return resBitClass;
}

/*
* Performs an and operation on the current BitClass and BitClass c.
*/
public BitClass and(BitClass c) {
BitClass resBitClass = new BitClass(bits);
for(int i = 0; i < b.length; i++)
resBitClass.b[i] = b[i] & c.b[i];
resBitClass.bitsSet = resBitClass.countBitsSet();
return resBitClass;
}

/*
* Performs an or operation on the current BitClass and BitClass c.
*/
public BitClass or(BitClass c) {
BitClass resBitClass = new BitClass(bits);
for(int i = 0; i < b.length; i++)
resBitClass.b[i] = b[i] | c.b[i];
resBitClass.bitsSet = resBitClass.countBitsSet();
return resBitClass;
}

/*
* Performs a xor operation on the current BitClass and BitClass c
*/
public BitClass xor(BitClass c) {
BitClass resBitClass = new BitClass(bits);
for(int i = 0; i < b.length; i++)
resBitClass.b[i] = b[i] ^ c.b[i];
resBitClass.bitsSet = resBitClass.countBitsSet();
return resBitClass;
}

/*
* Fills the BitClass with either 0 or 1.
*/
public BitClass fill(boolean set) {
BitClass resBitClass = this.copy();
long num = set ? 0xFFFFFFFFFFFFFFFFl : 0l;
for(int i = 0; i < resBitClass.length(); i++)
resBitClass.b[i] = num;

resBitClass.bitsSet = resBitClass.b.length * (64 & num);
return resBitClass;
}

/*
* printOptions prints every bit in the BitClass.
*/
public void printOptions() {
for(int i = 0; i < bits; i++) {
System.out.print(get(i));

}
System.out.println(" has " + countBitsSet() + ", " + bitsSet);
}

public long countBitsSet() {
/*
* We have to copy the current bits,
* because they will be changed by the counting algorithm.
*/
long j = 0, t = 0, tt;
int i = 0;
for(i = 0; i < b.length - 1; i++) {
tt = this.b[i];
for(t = 0; tt != 0; t++)
tt &= tt - 1;
j += t;
}

tt = b[i] & this.bitMask;
for(t = 0; tt != 0; t++)
tt &= tt - 1;

return j + t;
}

/*
* returns all the possiblities as an integer array.
*/

public int[] returnNumbers() {
int[] tmpInt = new int[(int)countBitsSet()];

int c = 0;
for(int i = 0; i < bits; i++)
if((b[i / 64] >> (i % 64) & 1) == 1)
tmpInt[c++] = i;


int[] resInt = new int[c];
for(int i = 0; i < c; i++) {
resInt[i] = tmpInt[i] + 1;
}

return resInt;
}

/*
* Returns true if the current BitClass equals BitClass a
*/
public boolean equals(BitClass a) {
if(a.bits != this.bits)
return false;
for(int i = 0; i < b.length; i++) {
if(a.b[i] != this.b[i])
return false;
}
return true;
}

@Override
public String toString() {
String s = new String();

for(int i = 0; i < bits; i++) {
s = s + get(i);
}

return s;
}
}


EDIT: The last bit code from a very old sudoku-java project. I didn't add any JavaDoc. (Which is also /* only afaik, and not //)

Also note now Nadeem's code needs a horizontal scroll bar - he goes past the 80 characters per line. :)

(No offence intended!)

senrath
10-02-2009, 11:19 PM
I've never had a teacher tell me to use /* for single comment lines. For multiple line comments, sure, but never single line comments.

And JavaDocs are different from inline commenting.

Wizzup?
10-02-2009, 11:22 PM
I've never had a teacher tell me to use /* for single comment lines. For multiple line comments, sure, but never single line comments.

And JavaDocs are different from inline commenting.

http://java.sun.com/docs/codeconv/html/CodeConventions.doc4.html#385

Seems they do use "//" for end-of-line comments. But never to comment on a line below the comment. (Which is what Nadeem did.)

senrath
10-02-2009, 11:26 PM
http://java.sun.com/docs/codeconv/html/CodeConventions.doc4.html#385

Seems they do use "//" for end-of-line comments. But never to comment on a line below the comment. (Which is what Nadeem did.)

Actually, in those examples they use // the same as they do /*..*/

It's personal preference, really. The only time when it actually matters is with multi-line comments, in which case you better not be using //

Wizzup?
10-02-2009, 11:40 PM
Actually, in those examples they use // the same as they do /*..*/

It's personal preference, really. The only time when it actually matters is with multi-line comments, in which case you better not be using //

I'd say they are very clear in the page.
Nevertheless, you'll find that most coders, hackers, teachers and students will use /*.

senrath
10-02-2009, 11:44 PM
I'd say they are very clear in the page.
Nevertheless, you'll find that most coders, hackers, teachers and students will use /*.

I guess all of my teachers have come from the minority, then.

Wizzup?
10-02-2009, 11:53 PM
I guess all of my teachers have come from the minority, then.

Most likely. What university?

senrath
10-02-2009, 11:54 PM
Virginia Polytechnic Institute and State University. Better known as Virginia Tech.

Wizzup?
10-03-2009, 12:20 AM
Some random (Really, I didn't pick them, I just chose random ones.) Kernel source files:
http://git.kernel.org/?p=linux/kernel/git/tytso/ext4.git;a=blob;f=include/linux/jbd2.h;h=f89668a21cc042e0dc9ad80c2ec8194c1b051622; hb=a7a6c3e58a984abae3c2202feb0b3fda826f3d7e
http://git.kernel.org/?p=linux/kernel/git/tytso/ext4.git;a=blob;f=fs/ext4/super.c;h=a275a800393855b61776b1c25806752d3681098b ;hb=a7a6c3e58a984abae3c2202feb0b3fda826f3d7e

Nadeem
10-03-2009, 12:45 AM
Nono wizzup is right actually, my cuzin (at Univeristy of Toronto, now graduated), told me the professors there take marks off actually when '//' are used, i only used them cuz im just used to using it, but yes '/*' is recommended. Infact ty wizzup for refreshing my memory i shall from now on use '/*' (:



~NS

senrath
10-03-2009, 12:48 AM
Nono wizzup is right actually, my cuzin (at Univeristy of Toronto, now graduated), told me the professors there take marks off actually when '//' are used, i only used them cuz im just used to using it, but yes '/*' is recommended. Infact ty wizzup for refreshing my memory i shall from now on use '/*' (:



~NS

Taking points off for using completely valid commenting seems stupid, to me.

Wizzup?
10-03-2009, 01:19 AM
Nono wizzup is right actually, my cuzin (at Univeristy of Toronto, now graduated), told me the professors there take marks off actually when '//' are used, i only used them cuz im just used to using it, but yes '/*' is recommended. Infact ty wizzup for refreshing my memory i shall from now on use '/*' (:



~NS

:)


Taking points off for using completely valid commenting seems stupid, to me.

I do agree with you; I thought exactly the same when I started Computer Science about a year ago, but they do take off marks when // is used. It really annoyed me. It's just nice to have a standard, so I've started using /* too. These days I have to mark about 20 Java Exercises a week, and I can tell you it's a pain if everyone uses a different coding standard. :)

For the interested:
There is also this rule about 80 chars per line, max. There are actually several reasons for this. One is that the default UNIX terminal is 80 chars wide, and wrapping lines is a pain. And when you print code, anything beyodn 80 chars is simply throw away.

To get back on topic: This, and mixing tabs and spaces are the major things one has to pay attention to. :)