today's material :
- event listener
listener is needed to make a button do something when clicked
using method addActionListener
here's the code...
learn from this and the java api...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class EventListener extends JFrame implements ActionListener{
JButton ok;
JButton cancel;
JButton add;
JTextField text;
JTextArea area;
String content;
public EventListener(){
setSize(640, 480);
setTitle("Simple Frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
ok = new JButton("OK");
ok.addActionListener(this);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
add = new JButton("Add to List");
add.addActionListener(this);
text = new JTextField(15);
area = new JTextArea();
JPanel pnlSouth = new JPanel(new GridLayout(2, 1));
JPanel pnlNorth = new JPanel(new FlowLayout());
JPanel pnl1 = new JPanel(new FlowLayout());
JPanel pnl2 = new JPanel(new FlowLayout());
pnlNorth.add(new Label("Customer List"));
pnlNorth.setBackground(Color.LIGHT_GRAY);
pnlSouth.add(pnl1);
pnlSouth.add(pnl2);
pnlSouth.setBackground(Color.LIGHT_GRAY);
pnl1.add(text);
pnl1.add(add);
pnl2.add(ok);
pnl2.add(cancel);
getContentPane().add(pnlNorth , BorderLayout.NORTH);
getContentPane().add(pnlSouth , BorderLayout.SOUTH);
getContentPane().add(area);
}
public static void main(String[] args) {
EventListener frame = new EventListener();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ok){
JOptionPane.showMessageDialog(this, "Button OK Clicked");
}
if(e.getSource() == cancel){
JOptionPane.showMessageDialog(this, "Button Cancel Clicked");
}
if(e.getSource() == add){
content = content + "\n" + text.getText();
area.setText(content);
}
}
}
thats all..............
Wednesday, April 28, 2010
Wednesday, April 21, 2010
week11 - starting GUI
its week 11 already..
one step further, Graphical User Interface we were taught...
here, this is what i got..
Graphical User Interface
- in java, GUI used by including classes from javax.swing and java.awt packages
- java.awt is the oldest type of GUI
- different from VB and Delphi, java's GUI can be used in wide selection of OS
Subclassing JFrame
- first step using GUI : making frame
- frame consist of : title, size[in pixel]
Trying out
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.*;
public class MySimpleFrame extends JFrame{
public MySimpleFrame() throws HeadlessException{
// setting the size of the frame
setSize(300, 200);
// setting the title of the frame
setTitle("My Simple Frame");
// setting the location of the frame
setLocation(100, 200);
// or
setLocationRelativeTo(null);
// setting the background color
getContentPane().setBackground(Color.blue);
// sets to terminate the program when the frame is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// initializing button 'ok'
JButton ok = new JButton();
ok.setSize(getMinimumSize());
ok.setText("OK");
ok.setBackground(Color.red);
// initializing button 'cancel'
JButton cancel = new JButton();
cancel.setSize(getMinimumSize());
cancel.setText("Cancel");
cancel.setBackground(Color.red);
// setting panel consist of button 'ok' and 'cancel'
JPanel pnlSouth = new JPanel(new FlowLayout());
add(pnlSouth, BorderLayout.SOUTH);
pnlSouth.setBackground(Color.BLACK);
pnlSouth.add(ok);
pnlSouth.add(cancel);
// makes the frame visible
setVisible(true);
}
public static void main(String[] args) {
MySimpleFrame msf = new MySimpleFrame();
}
}
i've put everything new with comment above it...
so it would be easy to learn from the code only...
that's all....
ciao...
one step further, Graphical User Interface we were taught...
here, this is what i got..
Graphical User Interface
- in java, GUI used by including classes from javax.swing and java.awt packages
- java.awt is the oldest type of GUI
- different from VB and Delphi, java's GUI can be used in wide selection of OS
Subclassing JFrame
- first step using GUI : making frame
- frame consist of : title, size[in pixel]
Trying out
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.*;
public class MySimpleFrame extends JFrame{
public MySimpleFrame() throws HeadlessException{
// setting the size of the frame
setSize(300, 200);
// setting the title of the frame
setTitle("My Simple Frame");
// setting the location of the frame
setLocation(100, 200);
// or
setLocationRelativeTo(null);
// setting the background color
getContentPane().setBackground(Color.blue);
// sets to terminate the program when the frame is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// initializing button 'ok'
JButton ok = new JButton();
ok.setSize(getMinimumSize());
ok.setText("OK");
ok.setBackground(Color.red);
// initializing button 'cancel'
JButton cancel = new JButton();
cancel.setSize(getMinimumSize());
cancel.setText("Cancel");
cancel.setBackground(Color.red);
// setting panel consist of button 'ok' and 'cancel'
JPanel pnlSouth = new JPanel(new FlowLayout());
add(pnlSouth, BorderLayout.SOUTH);
pnlSouth.setBackground(Color.BLACK);
pnlSouth.add(ok);
pnlSouth.add(cancel);
// makes the frame visible
setVisible(true);
}
public static void main(String[] args) {
MySimpleFrame msf = new MySimpleFrame();
}
}
i've put everything new with comment above it...
so it would be easy to learn from the code only...
that's all....
ciao...
Thursday, April 15, 2010
week 10
what i learn today :
array, which includes :
- array initialization
- array usage
- array in both 1 dimension and 2 dimensions
- array of objects
collections, which includes :
- arraylist
- hashset
- iteration
basic input output :
- how to write / save a file
- how to read from an exisiting file
thats all...
array, which includes :
- array initialization
- array usage
- array in both 1 dimension and 2 dimensions
- array of objects
collections, which includes :
- arraylist
- hashset
- iteration
basic input output :
- how to write / save a file
- how to read from an exisiting file
thats all...
Wednesday, April 7, 2010
week 9
back programming now...
its been 2 weeks...
here's what i got today..
characters and string
try this code
import javax.swing.*;
public class W09Chars {
public static void main(String[] args) {
char ch = 'Z';
byte b = 65;
JOptionPane.showMessageDialog(null, "ASCII code of character " + ch +
" is " + (int)ch);
JOptionPane.showMessageDialog(null, "Character with ASCII code " + b +
" is " + (char)b);
JOptionPane.showMessageDialog(null, ch + " is "
+ ((ch > b) ? "bigger" : "smaller")
+ " than " + (char)b);
}
}
highlight
((ch > b) ? "bigger" : "smaller")
same as
if(ch > b)
"bigger";
else
"smaller"
each character has a code in hexadecimal, which will be shown if the code is ran
back to topic,
character is a single digit while string is array consists of characters
comparing strings
case a : reffering to the same object
String word1 = "Surabaya"
String word2 = word1
both variable reffers to the same object, so
word1 == word2 is true
word1.equals(word2) is true
case b : reffering to different but identical object
String word1 = "Surabaya"
String word2 = new String("Surabaya")
which make
word1 == word2 is false, bacause the address is not the same
word1.equals(word2) is true, because the value is identical
case c : diferent value, different object
pattern matching
sometimes its needed to use a pattern
example 17-08-1945
the regular expression is:
[0-3][0-9]-[0-1][0-9]-[0-9]{4}
string buffer
needed because string is immutable or unchangable
any modification will produce new string
which will use more and more memory
thats all..
its been 2 weeks...
here's what i got today..
characters and string
try this code
import javax.swing.*;
public class W09Chars {
public static void main(String[] args) {
char ch = 'Z';
byte b = 65;
JOptionPane.showMessageDialog(null, "ASCII code of character " + ch +
" is " + (int)ch);
JOptionPane.showMessageDialog(null, "Character with ASCII code " + b +
" is " + (char)b);
JOptionPane.showMessageDialog(null, ch + " is "
+ ((ch > b) ? "bigger" : "smaller")
+ " than " + (char)b);
}
}
highlight
((ch > b) ? "bigger" : "smaller")
same as
if(ch > b)
"bigger";
else
"smaller"
each character has a code in hexadecimal, which will be shown if the code is ran
back to topic,
character is a single digit while string is array consists of characters
comparing strings
case a : reffering to the same object
String word1 = "Surabaya"
String word2 = word1
both variable reffers to the same object, so
word1 == word2 is true
word1.equals(word2) is true
case b : reffering to different but identical object
String word1 = "Surabaya"
String word2 = new String("Surabaya")
which make
word1 == word2 is false, bacause the address is not the same
word1.equals(word2) is true, because the value is identical
case c : diferent value, different object
pattern matching
sometimes its needed to use a pattern
example 17-08-1945
the regular expression is:
[0-3][0-9]-[0-1][0-9]-[0-9]{4}
string buffer
needed because string is immutable or unchangable
any modification will produce new string
which will use more and more memory
thats all..
Wednesday, March 17, 2010
weeK 6
menu :
- this keyword
- his keyword
- overloading and overriding
- polymorphism
- variable and method scoping
- parameter passing
- package
custom java class
- modifying string, int, calendar, array, we can do it by using existing classes
- when we found another unique entity, we need to custom a class
using THIS keyword
- THIS adalah reference ke variable yang ada pada object itu sendiri
- dengan kata lain THIS adalah self referencing pointer
THIS using example
public class Rectangle{
private double length;
private double width;
public Rectangle(){
}
public void setLength(double length){
this.length = length;
}
public void setWidth(double width){
this.width = width;
}
}
examine this following snippet
- Rectangle kotak = new Rectangle()
- Rectangle is class method, owned by class, no need for isntantiation
- to use : Rectangle.ClassMethod();
- kotak = object, the instance method, owned by instance, need instantiation to use
- to use : kotak.InstanceMethod();
to make an instance method
- public static double compute(double length, double width)
- by adding static there
- need argument, it cant use a variable from the object
overloaded method
- is when methods with same name, is made with different signature
- example, the method print
- print can do it for many kinds
multiple constructors
- using THIS in a constructor means its calling other constructor
- ex :
public Rectangle(){
this(0., 0.);
}
public Rectangle(double length){
this(length, length);
}
public Rectangle(double length, double width){
setLength(length);
setWidth(width);
}
- the first Rectangle calls the second, and the second call the third
static initializers
- make the code get executed when a java class is loaded into the java system
- ex :
public class Point {
private static long x , y ;
static{
x = System.currentTimeMillis();
y = ++x;
}
public Point() {}
public static long getXY(){
return x+y;
}
}
- the code inside static is executed firstly after the class is loaded
overriding
- modify the behaviour of superclass method by rewriting it in the subclass
- tehe signature must exactly be the same
- ex :
public class Box extends Rectangle{
private double height;
public Box(){
this(0. , 0. , 0.);
}
public Box(double length, double width, double height){
super(length, width);
this.height = height;
}
public Box(double size){
this(size, size, size);
}
- Box is the subclass of Rectangle
- using THIS called the variable in that class
- using SUPER called the variable in its superclass
polymorphism
- where there are more classes extending from one including the superclass,
and most used as a bridge to get a value from its method
- ex :
public class TestShapes {
public static void main(String[] args) {
Rectangle square, dice, brick, rectangle;
square = new Rectangle(4. );
dice = new Box(3. );
brick = new Box(4. ,3. , 2.);
rectangle = new Rectangle(2. , 1.);
System.out.println(square);
System.out.println(dice);
System.out.println(brick);
System.out.println(rectangle);
}
}
- this keyword
- his keyword
- overloading and overriding
- polymorphism
- variable and method scoping
- parameter passing
- package
custom java class
- modifying string, int, calendar, array, we can do it by using existing classes
- when we found another unique entity, we need to custom a class
using THIS keyword
- THIS adalah reference ke variable yang ada pada object itu sendiri
- dengan kata lain THIS adalah self referencing pointer
THIS using example
public class Rectangle{
private double length;
private double width;
public Rectangle(){
}
public void setLength(double length){
this.length = length;
}
public void setWidth(double width){
this.width = width;
}
}
examine this following snippet
- Rectangle kotak = new Rectangle()
- Rectangle is class method, owned by class, no need for isntantiation
- to use : Rectangle.ClassMethod();
- kotak = object, the instance method, owned by instance, need instantiation to use
- to use : kotak.InstanceMethod();
to make an instance method
- public static double compute(double length, double width)
- by adding static there
- need argument, it cant use a variable from the object
overloaded method
- is when methods with same name, is made with different signature
- example, the method print
- print can do it for many kinds
multiple constructors
- using THIS in a constructor means its calling other constructor
- ex :
public Rectangle(){
this(0., 0.);
}
public Rectangle(double length){
this(length, length);
}
public Rectangle(double length, double width){
setLength(length);
setWidth(width);
}
- the first Rectangle calls the second, and the second call the third
static initializers
- make the code get executed when a java class is loaded into the java system
- ex :
public class Point {
private static long x , y ;
static{
x = System.currentTimeMillis();
y = ++x;
}
public Point() {}
public static long getXY(){
return x+y;
}
}
- the code inside static is executed firstly after the class is loaded
overriding
- modify the behaviour of superclass method by rewriting it in the subclass
- tehe signature must exactly be the same
- ex :
public class Box extends Rectangle{
private double height;
public Box(){
this(0. , 0. , 0.);
}
public Box(double length, double width, double height){
super(length, width);
this.height = height;
}
public Box(double size){
this(size, size, size);
}
- Box is the subclass of Rectangle
- using THIS called the variable in that class
- using SUPER called the variable in its superclass
polymorphism
- where there are more classes extending from one including the superclass,
and most used as a bridge to get a value from its method
- ex :
public class TestShapes {
public static void main(String[] args) {
Rectangle square, dice, brick, rectangle;
square = new Rectangle(4. );
dice = new Box(3. );
brick = new Box(4. ,3. , 2.);
rectangle = new Rectangle(2. , 1.);
System.out.println(square);
System.out.println(dice);
System.out.println(brick);
System.out.println(rectangle);
}
}
Wednesday, March 10, 2010
5th week doin java
i'm getting used to it..
here's what i got today
selection statement and repetition
selection :
- using if statement
- using switch statement
- write boolean expression
- evaluate given boolean expression correctly
- nested if
- comparing objects
- selecting statement for given task
if syntax
- if ( )
else
relational operator
> more than
< less than
>= more than or equal to
<= less than or equal to
== equal to
!= not equal to
nested if
- if (comparing something){
if (comparing something){
do something
}
}
boolean operator
&& and
|| or
! not
boolean vars
- value : true / false
comparing object
- using ==
ex : String str1 = new String("java");
String str1 = new String("java");
str1 != str2
the location is different
ex : String str1 = new String("java");
str2 = str1
str1 == str2
the location is the same
- another way (to check only the value)
ex : if(str1.equals(str2)){
. . .
}
using switch case
- another branching statement with many possibilities
ex : switch ( N ){
case 1 : x = 30;
break;
case 2 : x = 40;
break;
case 3 : x = 50;
break;
default
trying something new
- using if statement and JOptionPane and also parseInt (converting String to Integer)
- here it is
IdealWeight.java
import javax.swing.JOptionPane;
public class IdealWeight {
public static void main(String[] args) {
int height,age;
double rec;
height = Integer.parseInt(JOptionPane.showInputDialog("input height : "));
age = Integer.parseInt(JOptionPane.showInputDialog("input age : "));
rec = (height - 100 + age / 10) * 0.9;
if(height > 140 && height < 230 && age > 0 && age < 100){
JOptionPane.showMessageDialog (null, "recom weight : " + rec );
}
else
JOptionPane.showMessageDialog (null, "error");
}
}
Repetition / looping
- using while - sentinel (have a certain statement to fulfill)
- using for - count controlled (have fixed times of loop)
commong looping mistakes
- off-by-one error
- make sure there is a statement which will terminate the loop
- make sure it loops just as many times as you wanted
while syntax
- while (statement){
do something
}
- while wont do the "something" unless the statement is fulfilled
do-while syntax
- do {
do something
}
- while(statement);
- do-while will do the "something" at least once before it evaluate the condition
for syntax
- for(starting condition; loop terminated condition; statement looped){
do something
}
a game to try on
not perfect, yet its enough for now
import javax.swing.JOptionPane;
public class HiLo {
private int secret,counter=0,guess;
public HiLo(){
secret = (int)(Math.random()*100);
JOptionPane.showMessageDialog(null, "I have a secret number, try and guess what it is");
while(counter<=6){
guess = Integer.parseInt(JOptionPane.showInputDialog("your guess : "));
if(guess < secret){
JOptionPane.showMessageDialog(null, "to low");
}
else if(guess > secret){
JOptionPane.showMessageDialog(null, "to high");
}
else if(guess == secret){
break;
}
counter++;
}
if(guess == secret){
JOptionPane.showMessageDialog(null, "my number is " + secret + ",you win");
}
else if(guess != secret)
JOptionPane.showMessageDialog(null, "my number is " + secret + ",you lost");
}
public static void main(String[] args) {
HiLo x = new HiLo();
}
}
thats all today...
here's what i got today
selection statement and repetition
selection :
- using if statement
- using switch statement
- write boolean expression
- evaluate given boolean expression correctly
- nested if
- comparing objects
- selecting statement for given task
if syntax
- if (
else
relational operator
> more than
< less than
>= more than or equal to
<= less than or equal to
== equal to
!= not equal to
nested if
- if (comparing something){
if (comparing something){
do something
}
}
boolean operator
&& and
|| or
! not
boolean vars
- value : true / false
comparing object
- using ==
ex : String str1 = new String("java");
String str1 = new String("java");
str1 != str2
the location is different
ex : String str1 = new String("java");
str2 = str1
str1 == str2
the location is the same
- another way (to check only the value)
ex : if(str1.equals(str2)){
. . .
}
using switch case
- another branching statement with many possibilities
ex : switch ( N ){
case 1 : x = 30;
break;
case 2 : x = 40;
break;
case 3 : x = 50;
break;
default
trying something new
- using if statement and JOptionPane and also parseInt (converting String to Integer)
- here it is
IdealWeight.java
import javax.swing.JOptionPane;
public class IdealWeight {
public static void main(String[] args) {
int height,age;
double rec;
height = Integer.parseInt(JOptionPane.showInputDialog("input height : "));
age = Integer.parseInt(JOptionPane.showInputDialog("input age : "));
rec = (height - 100 + age / 10) * 0.9;
if(height > 140 && height < 230 && age > 0 && age < 100){
JOptionPane.showMessageDialog (null, "recom weight : " + rec );
}
else
JOptionPane.showMessageDialog (null, "error");
}
}
Repetition / looping
- using while - sentinel (have a certain statement to fulfill)
- using for - count controlled (have fixed times of loop)
commong looping mistakes
- off-by-one error
- make sure there is a statement which will terminate the loop
- make sure it loops just as many times as you wanted
while syntax
- while (statement){
do something
}
- while wont do the "something" unless the statement is fulfilled
do-while syntax
- do {
do something
}
- while(statement);
- do-while will do the "something" at least once before it evaluate the condition
for syntax
- for(starting condition; loop terminated condition; statement looped){
do something
}
a game to try on
not perfect, yet its enough for now
import javax.swing.JOptionPane;
public class HiLo {
private int secret,counter=0,guess;
public HiLo(){
secret = (int)(Math.random()*100);
JOptionPane.showMessageDialog(null, "I have a secret number, try and guess what it is");
while(counter<=6){
guess = Integer.parseInt(JOptionPane.showInputDialog("your guess : "));
if(guess < secret){
JOptionPane.showMessageDialog(null, "to low");
}
else if(guess > secret){
JOptionPane.showMessageDialog(null, "to high");
}
else if(guess == secret){
break;
}
counter++;
}
if(guess == secret){
JOptionPane.showMessageDialog(null, "my number is " + secret + ",you win");
}
else if(guess != secret)
JOptionPane.showMessageDialog(null, "my number is " + secret + ",you lost");
}
public static void main(String[] args) {
HiLo x = new HiLo();
}
}
thats all today...
Wednesday, March 3, 2010
4th
so sleepy..
hv nothing to else say other than what i got at class...
here it is...
menu:
-argument/parameters
-passing obj to method
-constructor
-info hiding dan visibility modifiers
-local vars
info hiding
-the differences are between public or private
-with public,the info is accesible for other class
-with private it is not
-to access it,we need to use method
method
-syntax
( )
-arg# is the parameters which given the method a value to process
-there can be multiple parameters in a method by adding comma between each parameters
get the return value from method
-example
public double getBalance(){
return balance;
}
constructor
-is a special method thats executed when a new instance of class is created
-generated by compiler automatically when the file compiled
passing obj to method
-using object as a parameter in a method
local variables
-generated within a method,known only to that method
-example
public void swapBalance(Account vice,Account versa){
//tempBalance is a local var
double tempBalance=vice.getBalance();
vice.setBalance(versa.getBalance());
versa.setBalance(tempBalance);
thats all...
goin to sleep...
hv nothing to else say other than what i got at class...
here it is...
menu:
-argument/parameters
-passing obj to method
-constructor
-info hiding dan visibility modifiers
-local vars
info hiding
-the differences are between public or private
-with public,the info is accesible for other class
-with private it is not
-to access it,we need to use method
method
-syntax
-arg# is the parameters which given the method a value to process
-there can be multiple parameters in a method by adding comma between each parameters
get the return value from method
-example
public double getBalance(){
return balance;
}
constructor
-is a special method thats executed when a new instance of class is created
-generated by compiler automatically when the file compiled
passing obj to method
-using object as a parameter in a method
local variables
-generated within a method,known only to that method
-example
public void swapBalance(Account vice,Account versa){
//tempBalance is a local var
double tempBalance=vice.getBalance();
vice.setBalance(versa.getBalance());
versa.setBalance(tempBalance);
thats all...
goin to sleep...
Wednesday, February 24, 2010
3rd day
- headache , bad mood , dnt want to write anything at all -
- yet i have to -
what i got :
- review, the simplest code
public class Simplest{
public static void(String[] args){
//do nothing(cant be ran without method)
}
}
- today's menu
vars
arithmethic expressions
standard I/0
math class
gregorianCalendar Class
- public void doPaint(int colour);
void means there is no returned value, so the code above is called a procedure
- starting out, basic coding
public class Calculate{
public static void main(String[] args){
//set the value
//calculate
//print out the result
}
}
- vars
- types
- byte
- short
- int
- long
- float
- double
- boolean
- char
- declaration
syntax =
ex = boolean a;
int x,y;
char c;
- initialization
syntax = =
ex = a=true;
x=10;
c="you";
- code example
public class Calculate{
public static void main(String[] args){
//set the value
int income = 500000, expense = 270000;
float base = 2.7f;
float height;
int saldo;
float area;
height = 3.1f;
//calculate
saldo = income - expense;
area = (float)1/2 * base * height;
//print out the result
System.out.println("My money now = " + saldo);
System.out.println("Triangle area = " + area);
}
}
- the output should be like this
My money now = 230000
Triangle area = 4.185
- every vars should have a type
- the six numeric data types differ in the precisions of values they can store in memory
byte , short , int , long , float , double
smallest < < < < < < < < < largest
- number manipulating, based on precedence rules from the highest to lowest
- subexpression ; ( )
- unary operator ; +,- ; plus and minuses of the numbers
- multiplicative operator ; *,/
- additive operator ; +,- ; addition and substraction
- type casting
if x is float, and y is int, x + y is float
its called mixed expression, which will take the highest expression which is float
- explicit type casting
syntax - ()
example- (float) x / 5
(int) (x / y * 5.0)
- implicit type casting
example- double y = 5 + 7;
its adding 5 with 7 first, then promote it to double type variable
remember that it is a promotion, and a demotion is not allowed
- constants
means a variable with an unchanged value, use uppercase
syntax - final =
example- final PI = 3,1472;
- type mismatch
when a variable is an int, and when the value will be used for a string variable,
it will be conduct a type mismacth
- type conversion - wrapper classes
used to convert numeric into string and vice versa
- code example
public class CrossType{
public static void main(String[] args){
int age;
age = Integer.parseInt(args[0]);
age += 5;
System.out.println("Your age 5 years later : " + age);
}
}
- other type conversion, to :
- integer parseInt
- long parseLong
- float parseFloat
- double parseDouble
remember to make the value converted is conversible
- overloaded operator +
strOutput = "test" + 1 + 2;
the output will be "test12"
strOutput = 1 + 2 + "test";
the output will be "3test"
- standard Input/Output, code example
import java.util.Scanner;
public class MyScanner{
public static void main(String[] args){
System.out.print("Your age is now = ");
Scanner myScanner = new Scanner(System.in);
int age = myScanner.nextInt();
age += 5;
System.out.println("In the 5 years, your age will be " + age);
}
}
- math class
math class in java.lang package contains method for math functions
- code example
import java.util.Scanner;
public class MyMath{
public static void main(String[] args){
double num, x, y;
. . .
num = Math.sqrt(Math.max(x,y) + 3.14);
}
}
- gregorian calendar class
- code example
import java.util.GregorianCalendar;
public class MyCalendar{
public static void main(String[] args){
GregorianCalendar now = new GregorianCalendar();
System.out.println(" today is " + now.get(now.DATE) +
"/" + now.get(now.MONTH) +
"/" + now.get(now.YEAR));
}
}
thats all...
- yet i have to -
what i got :
- review, the simplest code
public class Simplest{
public static void(String[] args){
//do nothing(cant be ran without method)
}
}
- today's menu
vars
arithmethic expressions
standard I/0
math class
gregorianCalendar Class
- public void doPaint(int colour);
void means there is no returned value, so the code above is called a procedure
- starting out, basic coding
public class Calculate{
public static void main(String[] args){
//set the value
//calculate
//print out the result
}
}
- vars
- types
- byte
- short
- int
- long
- float
- double
- boolean
- char
- declaration
syntax =
ex = boolean a;
int x,y;
char c;
- initialization
syntax =
ex = a=true;
x=10;
c="you";
- code example
public class Calculate{
public static void main(String[] args){
//set the value
int income = 500000, expense = 270000;
float base = 2.7f;
float height;
int saldo;
float area;
height = 3.1f;
//calculate
saldo = income - expense;
area = (float)1/2 * base * height;
//print out the result
System.out.println("My money now = " + saldo);
System.out.println("Triangle area = " + area);
}
}
- the output should be like this
My money now = 230000
Triangle area = 4.185
- every vars should have a type
- the six numeric data types differ in the precisions of values they can store in memory
byte , short , int , long , float , double
smallest < < < < < < < < < largest
- number manipulating, based on precedence rules from the highest to lowest
- subexpression ; ( )
- unary operator ; +,- ; plus and minuses of the numbers
- multiplicative operator ; *,/
- additive operator ; +,- ; addition and substraction
- type casting
if x is float, and y is int, x + y is float
its called mixed expression, which will take the highest expression which is float
- explicit type casting
syntax - (
example- (float) x / 5
(int) (x / y * 5.0)
- implicit type casting
example- double y = 5 + 7;
its adding 5 with 7 first, then promote it to double type variable
remember that it is a promotion, and a demotion is not allowed
- constants
means a variable with an unchanged value, use uppercase
syntax - final
example- final PI = 3,1472;
- type mismatch
when a variable is an int, and when the value will be used for a string variable,
it will be conduct a type mismacth
- type conversion - wrapper classes
used to convert numeric into string and vice versa
- code example
public class CrossType{
public static void main(String[] args){
int age;
age = Integer.parseInt(args[0]);
age += 5;
System.out.println("Your age 5 years later : " + age);
}
}
- other type conversion, to :
- integer parseInt
- long parseLong
- float parseFloat
- double parseDouble
remember to make the value converted is conversible
- overloaded operator +
strOutput = "test" + 1 + 2;
the output will be "test12"
strOutput = 1 + 2 + "test";
the output will be "3test"
- standard Input/Output, code example
import java.util.Scanner;
public class MyScanner{
public static void main(String[] args){
System.out.print("Your age is now = ");
Scanner myScanner = new Scanner(System.in);
int age = myScanner.nextInt();
age += 5;
System.out.println("In the 5 years, your age will be " + age);
}
}
- math class
math class in java.lang package contains method for math functions
- code example
import java.util.Scanner;
public class MyMath{
public static void main(String[] args){
double num, x, y;
. . .
num = Math.sqrt(Math.max(x,y) + 3.14);
}
}
- gregorian calendar class
- code example
import java.util.GregorianCalendar;
public class MyCalendar{
public static void main(String[] args){
GregorianCalendar now = new GregorianCalendar();
System.out.println(" today is " + now.get(now.DATE) +
"/" + now.get(now.MONTH) +
"/" + now.get(now.YEAR));
}
}
thats all...
Wednesday, February 17, 2010
Second Day - OOP
-Struggle and that's how we live-
i'm back and as confused as ever..
first time dealing with java, yet im used to programming with C...
on second thought, maybe im getting the hang of it...
since im writing this in class while doing try and error with java...
lol...thats how human is...
developing as time movin forward...
okay, what i got today :
- given a problem, there is a drugstore selling 3 kinds of drug : generic, bubuk, pill...
generic = 1 times usual price, just take the drug
bubuk = 3 times usual price, cook it with water
pill = 4 times usual price, take it by drinking water, minimum purchase = 10 pills
- making 4 classes consist of drug, generic, bubuk, and pill [in UML and notepad]...
- making one new file [controller.java] to connect the subclass to the superclass
- compile them..
- run them...
here i will show you drug, generic, and controller
Drug.java
public class Drug {
/*plz name this class Drug.java*/
/*DEFAULT String = kosong = string x =""; */
String kode = "";
String bentuk = "";
/*DEFAULT int = kosong = int x=0; */
//this 2 vars will be used by the other java file, since this one is the superclass
int harga=1;
String caraMinum="";
//setter
public void setHarga(int harga){
this.harga = harga;
}
//getter
public int getHarga(){
return harga;
}
public static void main(String[] args){
//do something
}
}
Pill.java
public class Pill extends Drug{
int minimumPembelian = 10;
/* method priceMultiplier used for changing the price to 4 times usual*/
public void setMultiplier(){
harga=harga*4;
}
public void isiCaraMinum(){
caraMinum="pakai air putih";
}
}
**for Generic.java and Bubuk.java, the file is similar to Pill.java, but change every "Pill" to "Generic" or "Bubuk"..
Controller.java
public class Controller{
/* this class is used to call previous class : Drug & Pill*/
public static void main(String[] args){
Pill myPill = new Pill();
myPill.setMultiplier();
myPill.isiCaraMinum();
System.out.println("Harga pil = " + myPill.harga);
System.out.println("cara minum =" + myPill.caraMinum);
Generic myGeneric = new Generic();
myGeneric.setMultiplier();
myGeneric.isiCaraMinum();
System.out.println("Harga generik = " + myGeneric.harga);
System.out.println("cara minum =" + myGeneric.caraMinum);
Bubuk myBubuk = new Bubuk();
myBubuk.setMultiplier();
myBubuk.isiCaraMinum();
System.out.println("Harga bubuk = " + myBubuk.harga);
System.out.println("cara minum = " + myBubuk.caraMinum);
}
}
thats it...
to run it, see my first day...
c u next week...
i'm back and as confused as ever..
first time dealing with java, yet im used to programming with C...
on second thought, maybe im getting the hang of it...
since im writing this in class while doing try and error with java...
lol...thats how human is...
developing as time movin forward...
okay, what i got today :
- given a problem, there is a drugstore selling 3 kinds of drug : generic, bubuk, pill...
generic = 1 times usual price, just take the drug
bubuk = 3 times usual price, cook it with water
pill = 4 times usual price, take it by drinking water, minimum purchase = 10 pills
- making 4 classes consist of drug, generic, bubuk, and pill [in UML and notepad]...
- making one new file [controller.java] to connect the subclass to the superclass
- compile them..
- run them...
here i will show you drug, generic, and controller
Drug.java
public class Drug {
/*plz name this class Drug.java*/
/*DEFAULT String = kosong = string x =""; */
String kode = "";
String bentuk = "";
/*DEFAULT int = kosong = int x=0; */
//this 2 vars will be used by the other java file, since this one is the superclass
int harga=1;
String caraMinum="";
//setter
public void setHarga(int harga){
this.harga = harga;
}
//getter
public int getHarga(){
return harga;
}
public static void main(String[] args){
//do something
}
}
Pill.java
public class Pill extends Drug{
int minimumPembelian = 10;
/* method priceMultiplier used for changing the price to 4 times usual*/
public void setMultiplier(){
harga=harga*4;
}
public void isiCaraMinum(){
caraMinum="pakai air putih";
}
}
**for Generic.java and Bubuk.java, the file is similar to Pill.java, but change every "Pill" to "Generic" or "Bubuk"..
Controller.java
public class Controller{
/* this class is used to call previous class : Drug & Pill*/
public static void main(String[] args){
Pill myPill = new Pill();
myPill.setMultiplier();
myPill.isiCaraMinum();
System.out.println("Harga pil = " + myPill.harga);
System.out.println("cara minum =" + myPill.caraMinum);
Generic myGeneric = new Generic();
myGeneric.setMultiplier();
myGeneric.isiCaraMinum();
System.out.println("Harga generik = " + myGeneric.harga);
System.out.println("cara minum =" + myGeneric.caraMinum);
Bubuk myBubuk = new Bubuk();
myBubuk.setMultiplier();
myBubuk.isiCaraMinum();
System.out.println("Harga bubuk = " + myBubuk.harga);
System.out.println("cara minum = " + myBubuk.caraMinum);
}
}
thats it...
to run it, see my first day...
c u next week...
Wednesday, February 10, 2010
Object Oriented - 1st day
Now is the time to shape your stories! Your fate is in your hands!!
- Auron, Final Fantasy X -
Morning Class - Early Rise - yeah, whatever...
1st OOP class and here's what i've got...
open it, read it, whatever....hope u got what u need....
OOP
11 february 2010
class and objects
class -> gambaran umum akan sesuatu dengan ciri2 tertentu
ex : students, cats
object -> sesuatu yang lebih spesifik berdasarkan ciri2 dari class
ex : edward, garfield
properties and method
properties : ciri2nya, misal u/ cats -> color, weight, race
ada 2 properties :
- variable : berubah-ubah
- constant : ga bisa berubah
method : apa yang bisa dilakukan, misal u/ cats -> eat, jump, walk
ada 2 jenis :
- without argument/value, ex : jump()
- with argument/value, ex : jump(5) -> jump 5 times
inheritance
inheritance : mekanisme OOP dimana ada 2 atau lebih entity yang beda tapi punya banyak kesamaan
- superclass/ancestor : yang bersifat lebih umum
- subclass/descendant : yang bersifat lebih khusus dengan sifat mirip dengan superclass
software engineering
seperti membangun sesuatu, perlu disiplin ilmu, perlu langkah dan desain, langkah/stages nya :
- analysis : cari gambaran umum nya
- design : di bentuk design nya
- coding : programmingnya
- testing : di tes
- operation and maintenance : bagaimana di pakai orang lain dan perbaikan2nya
practice makes perfect
1. open cmd prompt
2. type "notepad HelloWorld.java" -> create new file
3. type :
public class HelloWorld {
public static void main(string[] args){
system.out.println("I Rule !");
system.out.println("The World !");
}
}
4. save
5. compile using "Javac HelloWorld.java"
6. run using "Java HelloWorld"
activating java
go to C:\Program Files\Java\jdk1.6.0_11\bin
go to system properties(right click @ my comp)
choose advanced
choose environment variables
double click path (system variables)
add ";C:\Program Files\Java\jdk1.6.0_11\bin" at the end of variable value
OK to the end
that's it for now...
It's ME !!!!
Life is a story...
And this is My Story...
My Story goes my way - and so does my life...
I dont care about mostly anything - just some in my opinion is important that i do...
Here goes My Story - and it goes MY WAY...
And this is My Story...
My Story goes my way - and so does my life...
I dont care about mostly anything - just some in my opinion is important that i do...
Here goes My Story - and it goes MY WAY...
Subscribe to:
Comments (Atom)
