This code will show a message written with '*' asterisks. You can do whatever message you want once you understand how the program flows. Just compile it and you' ll see.
public class LoveLetter {
public static void main(String[] args) {
method1();
method2();
method3();
}
static void method3() {
System.out.println("\n");
for(int i=0; i < 3; i++){
System.out.print("\t\t\t\t\t\t");
for(int j=0; j<9; j++){
if(j==0 || j==8){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println();
}
System.out.print("\t\t\t\t\t\t");
for(int i=0; i<8; i++){
if(i==0 || (i>=2 && i<=6)){
System.out.print(" ");
}
else if( i==1 || i==7){
System.out.print("*");
}
}
System.out.print("\n\t\t\t\t\t\t");
for(int i=0; i<6; i++){
if((i>=0 && i<=2) || (i==4)){
System.out.print(" ");
}
else if((i==3) || (i==5)){
System.out.print("*");
}
}
}
static void method2() {
System.out.printf("\t\t\t");
for(int i=0; i<7; i++){
if(i == 0 ){
System.out.print(" ");
}
else {
if( i>=1 && i<=3){
for(int j=0; j<1; j++){
System.out.print("*");
}
if(i == 3){
for(int k=0; k<3; k++){
System.out.print(" ");
}
}
}
if( i>=4 && i<=6){
for(int j=0; j<1; j++){
System.out.print("*");
}
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<11; i++){
if(i == 0){
System.out.print("*");
}
else {
if (i >= 1 && i<= 4){
System.out.print(" ");
}
else if( i==5){
System.out.print("*");
}
else if (i >= 6 && i<= 9) {
System.out.print(" ");
}
else {
System.out.print("*");
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<11; i++){
if(i == 0){
System.out.print("*");
}
else {
if (i >= 1 && i<= 9){
System.out.print(" ");
}
else {
System.out.print("*");
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<10; i++){
if(i == 0){
System.out.print(" ");
}
else {
if(i == 1){
System.out.print("*");
}
else if(i >= 2 && i <= 8){
System.out.print(" ");
}
else {
System.out.print("*");
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<8; i++) {
if (i >= 0 && i <= 2) {
System.out.print(" ");
}
else {
if (i == 3){
System.out.print("*");
}
else if(i >= 4 && i<=6){
System.out.print(" ");
}
else {
System.out.print("*");
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<7; i++){
if (i >= 0 && i <= 3) {
System.out.print(" ");
}
else {
if (i==4){
System.out.print("*");
}
else if(i==5){
System.out.print(" ");
}
else{
System.out.print("*");
}
}
}
System.out.println();
System.out.printf("\t\t\t");
for(int i=0; i<6; i++){
if(i>=0 && i<=4){
System.out.print(" ");
}
else {
System.out.print("*");
}
}
}
static void method1() {
System.out.print(" ");
for(int i=0; i<7; i++){
if(i == 0) {
for(int j=0; j<7; j++){
System.out.print("*");
}
}
else {
System.out.print(" ");
if(i == 5){
for(int j=0; j<7; j++){
System.out.print("*");
}
}
else {
if (i < 5) {
for(int j=0; j<1; j++){
System.out.print(" *");
}
}
}
} System.out.println();
}
}
}
Tuesday, April 2, 2013
Monday, November 12, 2012
Time Functions in Java!
This program shows real time update every second. It uses basic time functions and classes in java.
//code:
import javax.swing.Timer;
import java.awt.event.*;
import java.util.*;
public class Update implements ActionListener {
Timer t = new Timer(1000,this);
// every second
Update() {
t.start();
}
public static void main(String args[]) {
Update td = new Update();
// to keep the JVM running, a frame is needed
java.awt.Frame dummy = new java.awt.Frame();
dummy.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == t) {
System.out.println ("\007Tik Tak " + Calendar.getInstance().getTime());
}
}
}
Sunday, September 30, 2012
Decimal to Binary. How to program?
Sick and tired doing computations how decimal number will be converted in to binary code? Although its not really complicated then, taking much of your time is different. It is not necessary to used logic in manual computation but definitely "yes" in programming. Let me tell you how converting decimal number to binary code is done. For example, decimal number 12 will be converted manually. Use simple division operation.
12/2=6 remainder 0
6/2=3 remainder 0
3/2=1 remainder 1
1/2=0 remainder 1
Reading the reamainders from bottom to top, the binary value of 12 is 1100.
And here is the simple code for it.
import java.util.Scanner;
public class decimalToBinary{
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
System.out.print("Enter a Number: ");
int num = sn.nextInt();
String str ="";
for(;num>0;){
int binary = num%2;
str = Integer.toString(binary) + str;
num /= 2;
}
System.out.println("\nBinary Value: " + str);
}
}
You can try writing a program by doing the example above in vice-versa. (Binary to Decimal).How? Convert binary value 1100 to a decimal, it must be 12 suppostedly. In expanded form, substitute the decimal equivalents of all the symbols, multiply and add is appropriate. 1 1 0 0
1*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = 12
Wednesday, August 22, 2012
Primitive Data Types
These are primitive data types use in Java programming, primitive data types are the building blocks for more complicated types. In Java, its primitive types are portable across all computer flatforms that suppport Java. Unlike some other programming languages, programmers had to write separate versions of programs to support different platforms because the primitive data types were not guaranted to be identical from computer to computer. the value of memory of a specific data types might be different from one machine to another computer. In Java, for example, int values are always 32 bits (4 bytes).
type size in bits values standard
boolean 8 true/false
char 16 '\u0000' to '\uFFFF' (ISO unicode character set)
byte 8 -128 to 127
short 16 -32,768 to +32,767
int 32 -2,147,483,648
to 2,147,483,647
long 64 -9,223,372,036,854,775,808
to 9,223,372,036,854,775,808
float 32 -3,40292347E+38 (IEEE 754 floating point)
to 3,40292347E+38
double 64 -1,79769313486231570E+308 (IEEE 754 floating point)
to 1,79769313486231570E+308
For some related post please read How to declare variables?
Tuesday, August 7, 2012
(Painter)Event adapter and and their interfaces
Event adapter classes and the interfaces they implement
ComponentAdapter ComponenetListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListner
MouseAdapter MouseListener
MouseMotionListener MouseMotionListener
WindowAdapter WindowListener
This java program uses mouseDragged(not mouseMoved) event handler to create a simple drawing program.MouseMotionListener is defined as a subclass of MouseMotionAdapter, this already defines mouseMoved and mouseDraggedso simply override mouseDragged to provide drawing functionality.
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class(blue) Painter extends JFrame {
//store the coordinates of mouseDragged event
private int(blue) xValue=-10,yValue=-10;
public Painter() {
super ("Ullyses \"real myn tapei\" Cantos");
getContentPane().add(
new Label1("drag to draw"),BorderLayout.SOUTH);
addMouseMotionListener(
new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e)
{
valueNgX=e.getX();
valueNgY=e.getY();
//call repaint to initiate drawing
repaint();
}
}
);
setSize(600,300);
show();
}
@Override
public void paint(Graphics g)
{
g.fillOval(valueNgX,valueNgY,4,4);
}
public static void main(String args[])
{
Painter app=new Painter();
app.addWindowListener(
new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}//end
OUTPUT:
ComponentAdapter ComponenetListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListner
MouseAdapter MouseListener
MouseMotionListener MouseMotionListener
WindowAdapter WindowListener
This java program uses mouseDragged(not mouseMoved) event handler to create a simple drawing program.MouseMotionListener is defined as a subclass of MouseMotionAdapter, this already defines mouseMoved and mouseDraggedso simply override mouseDragged to provide drawing functionality.
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class(blue) Painter extends JFrame {
//store the coordinates of mouseDragged event
private int(blue) xValue=-10,yValue=-10;
public Painter() {
super ("Ullyses \"real myn tapei\" Cantos");
getContentPane().add(
new Label1("drag to draw"),BorderLayout.SOUTH);
addMouseMotionListener(
new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e)
{
valueNgX=e.getX();
valueNgY=e.getY();
//call repaint to initiate drawing
repaint();
}
}
);
setSize(600,300);
show();
}
@Override
public void paint(Graphics g)
{
g.fillOval(valueNgX,valueNgY,4,4);
}
public static void main(String args[])
{
Painter app=new Painter();
app.addWindowListener(
new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}//end
OUTPUT:
Monday, June 4, 2012
Product of two numbers without using Multiplication.
Sounds difficult, right? But if you will first take a second to understand, It would be easier for you to know what would be the best way to perform the operation. Simple logic will be applied, its simpler if you will use the operation itself. But for the sake of the logic and a basic looping technique, the program will look like this.
Code:
import javax.swing.JOptionPane;
public class Product{
public static void main (String [] args){
String firstNum, secondNum;
int num1, num2, product=0;
//convert string to int type variable
firstNum=JOptionPane.showInputDialog("enter first number");
num1=Integer.parseInt(firstNum);
secondNum=JOptionPane.showInputDialog("enter second number");
num2=Integer.parseInt(secondNum);
for(int i=0;i<num2;i++)
product += num1;
}
}//end
Code:
import javax.swing.JOptionPane;
public class Product{
public static void main (String [] args){
String firstNum, secondNum;
int num1, num2, product=0;
//convert string to int type variable
firstNum=JOptionPane.showInputDialog("enter first number");
num1=Integer.parseInt(firstNum);
secondNum=JOptionPane.showInputDialog("enter second number");
num2=Integer.parseInt(secondNum);
for(int i=0;i<num2;i++)
product += num1;
}
}//end
Friday, June 1, 2012
Square a number in JAVA.
Another simple program that will output the square of any input number. Im not in front of my JAVA application but i am pretty sure that it will work properly. This program will show the simple string to double type variable conversion in java programming.
Code:
import javax.swing.JOptionPane;
public class Square{
public static void main (String [] args){
String number;
Double num, squareofNumber;
number=JOptionPane.showInputDialog("Enter a number: ");
//convert string to double
num=Double.ParseDouble(number);
squareofNumber=num*num;
JOptionPane.showMessageDialog(null, "The square of the number you entered is "+square);
}
}
Code:
import javax.swing.JOptionPane;
public class Square{
public static void main (String [] args){
String number;
Double num, squareofNumber;
number=JOptionPane.showInputDialog("Enter a number: ");
//convert string to double
num=Double.ParseDouble(number);
squareofNumber=num*num;
JOptionPane.showMessageDialog(null, "The square of the number you entered is "+square);
}
}
Monday, May 21, 2012
FontTest using JFrame with Item Listener!
Here is another JFrame project using Listener methods. This program will prompt the user to select fonts of text and format. For questions please leave a message here. Some programmers understand a program by just reading its variable names that is why, by doing their jobs easier, programmers uses variable names which they can easily understand.
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SampleApplet extends JFrame{
JTextField lalagyanNgInfo;
JCheckBox italic,bold;
public Applet()
{
super("Item Listener (FONTS)");
Container c=getContentPane();
c.setLayout(new FlowLayout());
lalagyanNgInfo=new JTextField ("palit font",20);
lalagyanNgInfo.setFont(new Font("TimesRoman",Font.PLAIN,14));
c.add(lalagyanNgInfo);
//create Checkbox
bold=new JCheckBox("bold");
c.add(bold);
italic=new JCheckBox("italic");
c.add(italic);
CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener(handler);
italic.addItemListener(handler);
}//End of public Applet
public static void main (String args[ ])
{
JCheckBox CheckBoxTest=new JCheckBox();
}
//ItemListener code
private class CheckBoxHandler implements ItemListener{
private int styleBold=Font.PLAIN;
private int styleItalic=Font.PLAIN;
public void itemStateChanged(ItemEvent e)
{
if (e.getSource( )==bold)
if (e.getStateChange( )==ItemEvent. SELECTED )
styleBold=Font.BOLD;
else
styleBold=Font.PLAIN;
if (e.getSource( )==italic)
if (e.getStateChange( )==ItemEvent.SELECTED)
styleItalic=Font.ITALIC;
else
valItalic = Font.PLAIN;
lalagynNgInfo.setFont(new Font("TimesRoman",styleBold + styleItalic,14));
lalagyanNgInfo.repaint( );
}
}
}
Tuesday, May 15, 2012
Logical symbols in JAVA and its uses.
These are some logical symbols and uses of them in JAVA. I made a list of it in a program so you can easily understand its uses and functions. I also used methods under class swing for output manageability.
CODE:
import javax.swing.*;
public class Logicaloperators {
public static void main(String[] args) {
JTextArea textArea=new JTextArea (15,18);
JScrollPane scroller=new JScrollPane(textArea);
String infoSaTextArea="";
//infoSaTextArea (s) below must be a single line statement
infoSaTextArea+="Logical AND( && )"+"\nfalse && false: "+( false && false )+"\nfalse && true: "+( false && true )+"\ntrue && false: "+( true && false )+"\ntrue && true: "+( true && true );
infoSaTextArea+="\n\nLogical OR( || )"+"\nfalse || false: "+( false || false )+"\nfalse || true: "+( false || true )+"\ntrue || false: "+( true || false )+"\ntrue || true: "+( true || true );
infoSaTextArea+="\n\nBoolean Logical AND( & )"+"\nfalse & false: "+( false & false )+"\nfalse & true: "+( false & true )+"\ntrue & false: "+( true & false )+"\ntrue & true: "+( true & true );
infoSaTextArea+="\n\nBoolean Logical Inclusive OR( | )"+"\nfalse|false: "+( false | false )+"\nfalse | true: "+( false | true )+"\ntrue | false: "+( true | false )+"\ntrue | true: "+( true | true );
infoSaTextArea+="\n\nBoolean Logical Exclusive OR( ^ )"+"\nfalse ^ false: "+( false ^ false )+"\nfalse ^ true: "+( false ^ true )+"\ntrue ^ false: "+( true ^ false )+"\ntrue ^ true: "+( true ^ true );
infoSaTextArea+="\n\nLogical NOT( ! )"+"\n!false: "+(!false)+"\n!true: "+(!true);
textArea.setText(infoSaTextArea);
JOptionPane.showMessageDialog(null,scroller,"Truth Table",JOptionPane.INFORMATION_MESSAGE);
}
}
Saturday, May 12, 2012
Reverse Input Integer
It would be better for us newbies in JAVA programming to have codes and run it in your own. Even in a longest or in the simplest way you can, as long as the computer can understand. In every program in JAVA or even in other languages, there are lot of ways you may use to make the program working.
Example program written below will reverse an input user' s number(integer). For testing, if the user input the number 123, the program will then output 321.
import javax.swing.JOptionPane;
//Reverse.java
public class Reverse {
public static void main(String[] args) {
int number,remainder;
String s,baligtad="";
s=JOptionPane.showInputDialog("Maglagay ng number: ");
//convert string (s) to integer (number)
number=Integer.parseInt(s);
//use "num" for the original value
int num=number;
do{
remainder=number%10;
number/=10;
baligtad+=remainder;
}while(number>0);
//If you use "number" isntead "num", "0" will be the output output and not the number input
JOptionPane.showMessageDialog(null,"number: "+num+"\nreversed: "+baligtad);
}
}
OUTPUT:
Example program written below will reverse an input user' s number(integer). For testing, if the user input the number 123, the program will then output 321.
import javax.swing.JOptionPane;
//Reverse.java
public class Reverse {
public static void main(String[] args) {
int number,remainder;
String s,baligtad="";
s=JOptionPane.showInputDialog("Maglagay ng number: ");
//convert string (s) to integer (number)
number=Integer.parseInt(s);
//use "num" for the original value
int num=number;
do{
remainder=number%10;
number/=10;
baligtad+=remainder;
}while(number>0);
//If you use "number" isntead "num", "0" will be the output output and not the number input
JOptionPane.showMessageDialog(null,"number: "+num+"\nreversed: "+baligtad);
}
}
OUTPUT:
Friday, May 11, 2012
Control Structures in JAVA!
There are three(3) control structures use in java that can be used in some specific conditions.
1. if-else structure- use to implement an action in java under specified conditions.
*if selection structure does specific action under only one condition/relation.
Example:
If your grade is equal or greater than 50,print "pasado ka". if condition is TRUE, print, if FALSE
ignore/skip the next line.
code: if(grade=>50)
System.out.println("pasado ka");
*if-else selection structure gives an option on what will the compiler do(2 actions).
Example :
If your grade is equal or greater than 50,print "pasado ka". if false,print("bagsak").
code: if(grade=>50)
System.out.println("pasado ka");
else
System.out.println("bagsak");
*if structure also called single-selection structure
*if-else structure is called double-selection struture
2. switch structure- is a multiple-selection structure.
unlike if-else structure, switch does multiple actions can be performed.
Example: the user will choice the letter
A.If your grade is 50 above.
B.If your grade is 70 above.
C.If your grade is 80 above.
D.If your grade is 90 above.
code: char pagpipilian;
switch (pagpipilian){
case 'A':
System.out.println("mag-aral ka");
break;
case 'B':
System.out.println("mag-aral pa ng konti");
break;
case 'C':
System.out.println("masipag mag-aral");
break;
case 'D':
System.out.printlng("huwarang mag-aaral");
break;
default:
System.out.println("wala sa pagpipilian");
}
Common Programming Error: Forgetting to put break statement in a switch structure is a logic error.
3. the third structure is repeatition structures o looping.
Wednesday, May 9, 2012
How to use JScrollPane,ActionEvent, with JTextArea?Example code
It is important that you will first come to understand the program before you get to start coding it. What the program will execute and how will be its logic.
In this program,user can choose and select text elements in the first JTextArea and can copy in other JTextArea. There are two JTextArea in an object that you will create(t1 and t2). t1 where text was written and can be set in the codes and t2 where the selected text in t1 will be pasted.
//Filename:Copycat.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Copycat extends JFrame{
JTextArea t1,t2;
JButton copy;
public TxtAreaDemo()
{
super ("Tittle ng application!");
//Box ay subclass ng java.awt.Container
Box box=Box.createHorizontalBox();
String stringSaLoobNgt1="Eto yung mga kokopyahin\n"+
"na mga selected lines\n";
t1=new JTextArea(stringSaLoobNgt1,10,15);
//Ang JTextArea ay hindi nagpo-provide ng scrollbars
box.add(new JScrollPane(t1));//gumawa ng scrollbar
//yun selected text sa t1 will be copy sa t2
copy=new JButton("kopyahin dito>>");
copy.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
{
t2.setText(t1.getSelectedText());
}
});
box.add(copy);
//set t2
t2=new JTextArea(10,15);
t2.setEditable(false);
box.add(new JScrollPane(t2));
//Container ay collection ng components
Container c=getContentPane();
c.add(box);
setSize(425,200);
show();//use to show the object
}
public static void main(String[] args) {
TxtAreaDemo app=new TxtAreaDemo();
app.addWindowListener(
new WindowAdapter(){
public void widowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
OUTPUT:
Monday, May 7, 2012
How to use JTextArea in JAVA?
The JTextArea is a subclass under javax.swing, same as JOptionPane. It is a multi-line area that displays plain texts.
Code:
//import class na gagamitin, dahil me object kelangan din JOptionPane
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class JtextArea {
public static void main(String[] args){
//gumawa ng object(lalagyanNgInfo. Default na sukat(2,2)
JTextArea lalagyanNgInfo= new JTextArea(2,2);
//mga kelangan sa program
String unangString,
pangalawangString,
ilalagayNaInfo="";
int unangNumber,
pangalawangNumber,
sum,difference,product;
double quotient;
//string to integer convertion
unangString=JOptionPane.showInputDialog("unang number: ");
unangNumber=Integer.parseInt(unangString);
pangalawangString=JOptionPane.showInputDialog("pangalawang number: ");
pangalawangNumber=Integer.parseInt(pangalawangString);
//mga formula
sum=unangNumber+pangalawangNumber;
difference=unangNumber-pangalawangNumber;
product=unangNumber*pangalawangNumber;
quotient=unangNumber/pangalawangNumber;
//laman ng ilalagay na info sa object(lalagyanNgInfo)
ilalagayNaInfo+="sum\tdifference\tproduct\tquotient";
ilalagayNaInfo+="\n"+sum+"\t"+difference+"\t"+product+"\t"+quotient;
lalagyanNgInfo.setText(ilalagayNaInfo);
JOptionPane.showMessageDialog(null,lalagyanNgInfo,"Eto ang mga sagot!",JOptionPane.INFORMATION_MESSAGE);
}
}
OUTPUT: quotient is zero instead 0.xxxx because data type used in quotient is integer. We focused on JTextArea.
Sunday, April 29, 2012
Fibonacci Sequence in JAVA!example code
Here' s the fibonacci sequence. Q:What is fibonacci sequence?
A: This is a pattern of numbers wherein the next number is the sum of two previous number starts with zero(0).How to do this? A simple for looping will do. Here's the catch.
Code:
public class Fibonacci {
public static void main(String[] args) {
int sunodnaNumber = 1, //initialize
hulingNumber = 0, //initialize
sum;
System.out.println("Eto ang Fibonacci Sequence");
//you may use other LOOPING rules. click here.
//20 numbers in fibonacci
for(int i=0; i<20; i++){
System.out.println(sunodnaNumber);
sum = sunodnaNumber + hulingNumber;
hulingNumber = sunodnaNumber;
sunodnaNumber = sum;
}
}
}
A: This is a pattern of numbers wherein the next number is the sum of two previous number starts with zero(0).How to do this? A simple for looping will do. Here's the catch.
Code:
public class Fibonacci {
public static void main(String[] args) {
int sunodnaNumber = 1, //initialize
hulingNumber = 0, //initialize
sum;
System.out.println("Eto ang Fibonacci Sequence");
//you may use other LOOPING rules. click here.
//20 numbers in fibonacci
for(int i=0; i<20; i++){
System.out.println(sunodnaNumber);
sum = sunodnaNumber + hulingNumber;
hulingNumber = sunodnaNumber;
sunodnaNumber = sum;
}
}
}
More examples by request, basta kaya gawin ni author:)
More lessons to come.
If you have more something to add ikakagalak ko po.
SHARE and LEARN!
Sunday, April 22, 2012
How to use scanner in JAVA?
Q: How and What is the use of java.util.scanner in JAVA?
A: Scanner is most similar to How does BufferedReader class works?
BufferedReader is under "io" class while Scanner is under "util".
Since they have similarities, In this example, same problem will be solved as the link above.
//import the Scanner class
import java.util.Scanner;
//public class pangalanNgProject
public class Scan{
public static void main(String[] args) {
//set a Scanner name. (realmyn)
Scanner realmyn = new Scanner(System.in);
String pangalanNgUser;
System.out.println("anu pangalan mo? ");
pangalanNgUser=realmyn.nextLine();
System.out.println("kumusta ka " + pangalanNgUser+"?");
}
}
OUTPUT:
anu pangalan mo?
Juan
kumusta ka Juan?
Good Programming Practice:
Use variable names which you can easily understand for better coding.
A: Scanner is most similar to How does BufferedReader class works?
BufferedReader is under "io" class while Scanner is under "util".
Since they have similarities, In this example, same problem will be solved as the link above.
//import the Scanner class
import java.util.Scanner;
//public class pangalanNgProject
public class Scan{
public static void main(String[] args) {
//set a Scanner name. (realmyn)
Scanner realmyn = new Scanner(System.in);
String pangalanNgUser;
System.out.println("anu pangalan mo? ");
pangalanNgUser=realmyn.nextLine();
System.out.println("kumusta ka " + pangalanNgUser+"?");
}
}
OUTPUT:
anu pangalan mo?
Juan
kumusta ka Juan?
Good Programming Practice:
Use variable names which you can easily understand for better coding.
Wednesday, April 18, 2012
How to set DecimalFormat in JAVA?
Paano ba mag set ng decimal format tulad kapag ganito ang program decimals ? Diba ang dami figures? Para mai-set ng ayos depende sa gusto mo, eto basic program para mas madali maintindihan how it works. Use DeciFormat.
import java.text.DecimalFormat;
public class decimalFormat {
public static void main(String[] args) {
//set variable "point" sa gusto mo na format
DecimalFormat point=new DecimalFormat ("0.00");
//set value 'a' at 'b'
//declare as double, kasi pag int type ang variable walang decimal points ang output
double a=10,b=3;
double quotient=a/b;
//print output
System.out.println("the quotient is "+ point.format(quotient));
}
}Done!
Take note "point.format(quotient)" ,ganito ang pag gamit ng format na gusto mo. Kung basic na output code at hindi mo gagamitan ng decimal format ganito ang magiging output nyan.
output:
the quotient is 3.3333333333333335
SHARE and LEARN!
How to perform loops/iterations in JAVA?
In Java there are also different kinds of looping/iterations. But before that, why are we using such method? Loopings usually use to prevent or to avoid line redundancy in a program, by performing this techniques, you will be able to organize your program in a very simple way. For example, you will be printing 5 or more lines "Ako si Real Myn". You can code as simple as below, but how is it if you have to print more than this? A hundred?2 hundred?
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
Output:
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Are willing to type those lines and made sure you have got the right number?
Example: "Ako si Real Myn" in 20 times.
Solution 1: Do-While Loop
/*initialize integer type variable "counter" to 0,
ito ang taga bilang kung ilang ulit gagawin ang statement*/
int counter=0;
do //Gawin ito
{
System.out.println("Ako si Real Myn");
counter++; //magdagdag ng isa(1) ang counter sa tuwing uulit
}
while (counter<20); //Gawin (do), while counter is less than 20
Solution 2: For Loop
for (int counter=0;counter<20;counter++)
System.out.println("Ako si Real Myn");
Solution 3: While Loop
int counter=0;
while (counter<20)
{
System.out.println("Ako si Real Myn");
counter++;
}
Pwede gamitin kahit alin sa mga types of looping na ito para sa program, sa halip na ita-type mo paulit ulit un basic codes sa pag print ng line.
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
System.out.println("Ako si Real Myn");
Output:
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Ako si Real Myn
Are willing to type those lines and made sure you have got the right number?
Example: "Ako si Real Myn" in 20 times.
Solution 1: Do-While Loop
/*initialize integer type variable "counter" to 0,
ito ang taga bilang kung ilang ulit gagawin ang statement*/
int counter=0;
do //Gawin ito
{
System.out.println("Ako si Real Myn");
counter++; //magdagdag ng isa(1) ang counter sa tuwing uulit
}
while (counter<20); //Gawin (do), while counter is less than 20
Solution 2: For Loop
for (int counter=0;counter<20;counter++)
System.out.println("Ako si Real Myn");
Solution 3: While Loop
int counter=0;
while (counter<20)
{
System.out.println("Ako si Real Myn");
counter++;
}
Pwede gamitin kahit alin sa mga types of looping na ito para sa program, sa halip na ita-type mo paulit ulit un basic codes sa pag print ng line.
SHARE and LEARN!
Saturday, April 7, 2012
How to compute your age in JAVA?
Calendar and Date are often used when we are dealing with time/date. They are subclasses under java.util class.Date use for date storing while Calendar usually use for manipulating.
// first import Calendar
import java.util.Calendar;
public class HowYoungAreYou{
public static void main(String[]args){
//set current time and date,ngayon!kung anong date sa PC
Calendar now=Calendar.getInstance();
//set yung birthdate mo
Calendar before=Calendar.getInstance();
//halimbawa birthdate mo ay July 25,2000
before.set(2000,6,25);
/* month is an array,
and array start with 0-January,1-Febuary
therefore 2000,6,25 is July 25 2000*/
//convert time in milliseconds
//declare nowmillis and beforemillis in "long" integer
long nowmillis=now.getTimeInMillis();
long beforemillis=before.getTimeInMillis();
//find the difference of date in milliseconds
//declare also timemillis as "long" integer
long timemillis=nowmillis-beforemillis;
//compute/convert millisecond in to days
long days=timemillis/(24 * 60 * 60 * 1000);
//1000ms in a second,60 in a minute,60minute in an hour and 24hours in a day
//then days to years,365days in a year, declare in double for decimal decimal
double year=(double) (days/365d);
System.out.println("You are"+year+"year(s) old right now!);
}
}/Done
Output:
You are 11.70958904109589 year(s) old right now!
// first import Calendar
import java.util.Calendar;
public class HowYoungAreYou{
public static void main(String[]args){
//set current time and date,ngayon!kung anong date sa PC
Calendar now=Calendar.getInstance();
//set yung birthdate mo
Calendar before=Calendar.getInstance();
//halimbawa birthdate mo ay July 25,2000
before.set(2000,6,25);
/* month is an array,
and array start with 0-January,1-Febuary
therefore 2000,6,25 is July 25 2000*/
//convert time in milliseconds
//declare nowmillis and beforemillis in "long" integer
long nowmillis=now.getTimeInMillis();
long beforemillis=before.getTimeInMillis();
//find the difference of date in milliseconds
//declare also timemillis as "long" integer
long timemillis=nowmillis-beforemillis;
//compute/convert millisecond in to days
long days=timemillis/(24 * 60 * 60 * 1000);
//1000ms in a second,60 in a minute,60minute in an hour and 24hours in a day
//then days to years,365days in a year, declare in double for decimal decimal
double year=(double) (days/365d);
System.out.println("You are"+year+"year(s) old right now!);
}
}/Done
Output:
You are 11.70958904109589 year(s) old right now!
More examples by request
More lessons to come.
SHARE and LEARN!
Friday, March 30, 2012
How to add integers using JOptionPane in JAVA?
Add, kasi eto ang pinaka basic na operation, para mas madali maintindihan. Tandaan, ang programming ay parang mabait na bata :) masunurin at walang alinlangan gagawin exactly kung anu ang i-utos mo. Magsimula tayo sa pinaka basic. Ang addition.
//Addition
//Mag a-add ng dalawang integer from user's input
import javax.swing.JOptionPane;
//una, import muna ang gagamitin para sa JOptionPane
public class PangalanNgProject {
//Kelangan sakto sa filename kapag sinave na may .java extension
public static void main (String []args){
String number1,number2;
int unangNum,pangalawangNum,sum;
//magdeclare ng string at int na madali nyo maintindihan
number1=JOptionPane.showInputDialog("Unang number:");
//string for number1 "Unang number"
unangNum=Integer.parseInt(number1);
//convert string(number1) to integer(unangNum)
number2=JOptionPane.showInputDialog("Pangalawang number");
//string for number2 "Pangalawang number"
pangalawangNum=Integer.parseInt(number2);
//convert string(number2) to integer(pangalawangNum)
sum=unangNum+pangalawangNum;
//alam nyo na naman siguro mag add:)
JOptionPane.showMessageDialog(null,"Ang sagot ay:"+sum);
//bakit may keyword null? click mo ito!
}
}
//Addition
//Mag a-add ng dalawang integer from user's input
import javax.swing.JOptionPane;
//una, import muna ang gagamitin para sa JOptionPane
public class PangalanNgProject {
//Kelangan sakto sa filename kapag sinave na may .java extension
public static void main (String []args){
String number1,number2;
int unangNum,pangalawangNum,sum;
//magdeclare ng string at int na madali nyo maintindihan
number1=JOptionPane.showInputDialog("Unang number:");
//string for number1 "Unang number"
unangNum=Integer.parseInt(number1);
//convert string(number1) to integer(unangNum)
number2=JOptionPane.showInputDialog("Pangalawang number");
//string for number2 "Pangalawang number"
pangalawangNum=Integer.parseInt(number2);
//convert string(number2) to integer(pangalawangNum)
sum=unangNum+pangalawangNum;
//alam nyo na naman siguro mag add:)
JOptionPane.showMessageDialog(null,"Ang sagot ay:"+sum);
//bakit may keyword null? click mo ito!
}
}
Kapag subtract, multiplication or division palitan lang ng operation. O pwede din pag sama samahin nyo na lahat. At lagyan ng mga condition kung kailangan.
More examples by request, basta kaya gawin ni author:)
More lessons to come.
If you have more something to add ikakagalak ko po.
SHARE and LEARN!
Thursday, March 22, 2012
How to use JOptionPane in java?
Little too busy in school:)
From the past few lessons here, we are running JAVA programs in cmd/text only interfaces. Now we will learn how JOptionPane class in java works to have an object oriented program.
//import JOptionPane class
import javax.swing.JOptionPane;
public class Joptionpanejava {
public static void main(String[] args) {
//e main line for JOptionPane
JOptionPane.showMessageDialog(null,"WELCOME to magJAVAtayo!");
}
}
// showMesssageDialog method is under JOptionPane class and this method requires two arguments. If a method requiures multiple arguments, these must be separated by comma(,). And the first argument will always be the keyword null
JOptionPane.showMessageDialog(first argument , second argument);
Output should be like this:
If you want to print from user's input, edit the code to this.
// declare string variable
String string1;
//use showInputDialog method
string1=JOptionPane.showInputDialog("Ano ang pangalan mo?");
JOptionPane.showMessageDialog(null,"Hi "+string1+"! Kumusta?");
try this code to see the output.
From the past few lessons here, we are running JAVA programs in cmd/text only interfaces. Now we will learn how JOptionPane class in java works to have an object oriented program.
//import JOptionPane class
import javax.swing.JOptionPane;
public class Joptionpanejava {
public static void main(String[] args) {
//e main line for JOptionPane
JOptionPane.showMessageDialog(null,"WELCOME to magJAVAtayo!");
}
}
// showMesssageDialog method is under JOptionPane class and this method requires two arguments. If a method requiures multiple arguments, these must be separated by comma(,). And the first argument will always be the keyword null
JOptionPane.showMessageDialog(first argument , second argument);
Output should be like this:
If you want to print from user's input, edit the code to this.
// declare string variable
String string1;
//use showInputDialog method
string1=JOptionPane.showInputDialog("Ano ang pangalan mo?");
JOptionPane.showMessageDialog(null,"Hi "+string1+"! Kumusta?");
try this code to see the output.
More examples by request, basta kaya gawin ni author:)
More lessons to come.
If you have more something to add ikakagalak ko po.
SHARE and LEARN!
Subscribe to:
Posts (Atom)







