Sunday, September 28, 2014

Chapter 2: Date and SimpleDateFormat

Date today;
today = new Date( );

JOptionPane.showMessageDialog(null, today.toString( ));

will display this current time format:
===========================
OUTPUT: Sun Sept 28 15:05:18 PDT 2014

----------------------------------------------------

If we want to display the month, day, and year in the MM/dd/YY shorthand format, such as 07/04/2013, we write


Date      today;
SimpleDateFormat    sdf;

today = new Date( );
sdf = new SimpleDateFormat("MM/dd/yy");

JOptionPane.showMessageDialog(null, sdf.format(today));
==================================
OUTPUT:
09/28/2014
----------------------------------------------------------
If we want to display September 28, 2014

Date      today;
SimpleDateFormat    sdf;

today = new Date( );
sdf = new SimpleDateFormat("MMMM dd,yyyy");

JOptionPane.showMessageDialog(null, sdf.format(today));
==================================
OUTPUT:
September 28, 2014
-------------------------------------------------------

If we want to display which day of the week today is, we can use the letter E as in

Date      today;
SimpleDateFormat    sdf;

today = new Date( );
sdf = new SimpleDateFormat("EEEE");

JOptionPane.showMessageDialog(null, sdf.format(today));
==================================
OUTPUT:
Sunday
-------------------------------------------------------
Show the output of this code:

   GregorianCalendar cal= new GregorianCalendar();
        
        System.out.print(cal.getTime());
        System.out.println(" ");
        System.out.println("\n YEAR:" + cal.get(Calendar.YEAR));
        System.out.println("\n MONTH:" + cal.get(Calendar.MONTH));
        System.out.println("\n DATE:" + cal.get(Calendar.DATE));
        System.out.println("\n Day of Year:" + cal.get(Calendar.DAY_OF_YEAR));
        System.out.println("\n Day of Month:" + cal.get(Calendar.DAY_OF_MONTH));
        System.out.println("\n Day of Week:" + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("\n Week of Month:" + cal.get(Calendar.WEEK_OF_MONTH));
        System.out.println("\n AM_PM:" + cal.get(Calendar.AM_PM));
        System.out.println("\n HOUR:" + cal.get(Calendar.HOUR));
        System.out.println("\n HOUR of Day:" + cal.get(Calendar.HOUR_OF_DAY));
        System.out.println("\n Minute:" + cal.get(Calendar.MINUTE));




Saturday, September 27, 2014

September 28, 2014 Quiz

1. Identify all errors in the following program
/*
Program Exercises1
Attempting to display a frame window
//
import swing.JFrame;
class Exercise 1 {
      public void Mail( ){
           JFrame frame;
           frame.setVisible(TRUE);

    }

}
2. Identify all errors in the following program
//
Program Exercise 2
Attempting to display a frame of size 300 by 200 pixels.
//
import Javax.Swing.*;
class two{
        public static void main method( ){
              myFrame JFrame;
              myFrame = new JFrame( );
              myFrame.setSize(300,200);
              myFrame.setVisible( );
      }
}


3. Identify all errors in the following program
/*
Program Exercise3
Attempting to display the number of characters in a given input.
*/
class three{
     public static void main( ) {
         String input;
        input=JOptionPane("input:");
    JOptionPane.showMessageDialog(null, "Input has " + input.length( ) + "characters");
   }
}


4. For each of these expressions, determine its result. Assume the value of text is a string Java Programming.
String text = "Java Programming";
a.) text.substring(0,4);
b.) text.length( );
c.) text.substring(8,12);
d.) text.substring(0,1) + text.substring(7,9)
e.)text.substring(5,6) + text.substring(text.length()-3,text.length( ))


5.) Write a Java application that displays the two messages I CAN DESIGN AND I CAN PROGRAM, using two separate lines.


Monday, December 10, 2012

Quick Check

#1. Write a code fragment to input the user's height in inches and assign the value to an int variable named height.

#2 Write a code fragment to input the user's weight in pounds and display the weight in kilograms, 1lb =453.592g.

Chapter 3: Sample program:Compute Area and Circumference

/*Chapter 3: Sample program:Compute Area and Circumference
*File: Ch3Circle.java
*/

import javax.swing.*;
class Ch3Circle{
public static void main( String[] args){

     final double PI = 3.14.159;

    String radiusStr;
    double radius, area, circumference;

      radiusStr = JoptionPane.showInputDialog(null, "Enter radius:");
   radius= Double.parseDouble(radiusStr);

//compute area and circumference

area= PI * radius * radius;
circumference = 2.0 * PI * radius;

JOptionPane.showMessageDialog(null, "Given Radius:" +radius + "\n"
                                                          + "Area:" +area+"\n"
                                                                 +"Circumference:"+circumference);
        }
}

Tuesday, December 4, 2012

Chapter 2. Getting Started with Java


Chapter 2. Getting Started with Java

Objectives:
·         Identify the basic components of Java programs
·         Write simple Java Program
·         Describe the process of creating and running Java Programs
·         Use the Date, SimpleDateFormat, String, and JOptionPane classes from the standard Java Packages.
·         Develop Java Programs, using the incremental development approach.

2.1 The first java program

Our first Java application program displays a window on the screen, as shown in the output below. The size of the window is set to 300pixels wide and 200pixels high. A pixel is a shorthand for picture element, and it is the standard unit of measurement for the screen resolution.

/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample1.java
*/
importjavax.swing.*;
class Ch2Sample1 {
public static void main( String[] args){
JFramemyWindow;
myWindow    =   new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
    }
}


TAKE MY ADVICE
This will not concern the majority of you, but if you are using a Java development tool that does not let you stop a running program easily, then insert the statement

                myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


after

                myWindow.setVisible(true);


so the program terminates automatically when the frame window is closed.





HELPFUL REMINDERS
A Java program is composed of comments, import statements, and class declarations.
HELPFUL REMINDERS
To use an object in a program, first we declare and create an object, and then we send messages to it.

OBJECT DECLARATION

Object declaration syntax

<class name> <object names>;


                Where <object names> is a sequence of object names separated by commas and <class name> is the name of a class to which these objects belong. Here’s how the general syntax is matched to the object declaration of the program:


 






JFrame                                 myWindow  ;

More examples:
Account               checking;
Customer            john,jack,jill;


OBJECT CREATION

Object creation syntax

<object name>              =  new <class name> (<argument>);


                Where <object name> is the name of a declared object, <class name> is the name of the class to which the object  belongs, and <arguments> is a sequence of values passed to the new operation. Let’s match the syntax to the actual statement in the sample program:


 






myWindow         =             new       JFrame ();

Example of object declaration and object creation statements:

Customer          customer;

customer = new Customer(  );


Take my Advice
Instead of writing statements for object declaration and creation separately, we can combine them into one statement. We can write, for example.

                Student                              john      =             new Student( );

Instead of

                Student john;

                John      =             new      Student( ) ;


Quick Check
1.       Which of the following are invalid identifiers?
a.       one
b.      my Window
c.       1234
d.      DecafeLattePlease
e.      Hello
f.        JAVA
2.       What’s wrong with the following code?
JFramemyWindow();
myWindow.setVisible(true);
3.       Which of the following statements is valid?
a.       myFirstWindow.setVisible{“true”);
b.      myFirstWindow.setVisible(true);








2.2 Program Components





Comments

Design Guidelines

Always aim for self-explanatory code. Do not attempt to make a poorly written code easier to read by comments. Good comments are not a substitute for good code. Bad code is bad, no matter how well your comments are written.
Take my advice
Comment markers are useful in disabling a portion of a program. Let’s say you find a portion that may be causing the program to crash, and you want to try out different code for the problem portion. Instead of replacing the whole problem portion with new code, you can leave the questionable code in the program by converting it into a “comment” with comment markers. You can remove the comment marketing if you need this code later.

Import statement
                The import statement allows the program to refer to classes defined in the designated  package without using the fully qualified class name



/*
Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample1.java
*/

importjavax.swing.*;

class Ch2Sample1 {
public static void main( String[] args){
JFramemyWindow;
myWindow    =   new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
    }
}

If no import statement

/*

Chapter 2 Sample Program: Displaying a Window
File: Ch2Sample1.java
*/
importjavax.swing.*;
class Ch2Sample1 {
public static void main( String[] args){

javax.swing.JFramemyWindow;

myWindow    =   new javax.swing.JFrame();

myWindow.setSize(300,200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
    }
}

Instead of using the expression javax.swing.JFrame to refer to the class, we can refer to it simply as

JFrame

By including the import statement

importjavax.swing.*;


You might want to know

                When we say “import a package”, it sounds as if we are copying all those classes into our programs. That is not the case. Importing a package is only a shorthand notation for referencing classes. The only effect of importing a package is the elimination of the requirement to use the fully qualified name. No classes are physically copied into our programs.
Class Declarations
Syntax code
                class<class name> {
                                <class member declarations>
                }
class Ch2Sample1 {

public static void main( String[] args){
JFramemyWindow;
myWindow    =   new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
    }
}

Method Declarations
Syntax code
                <modifiers><return type><method name> ( <parameter>  ){
                                <method body>
                }
Public static void main( String[] args){

JFramemyWindow;
myWindow    =   new JFrame();
myWindow.setSize(300,200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
    }
}

2.3 Edit-Compile-Run-Cycle


Step 1. Type in the program, using the editor, and save the program to a file. Use the name of the main class and the suffix .java for the filename. This file,in which the program is in a human-readable form, is called a source file.
Step 2. Compile the source file. This compiled version is called bytecode, and the file that contains bytecode is called bytecode file. The name of the compiler-generated bytecode file will have the suffix .class while its prefix is the same as the one for the source file.

Step 3. Execute the bytecode file. A Java interpreter will go through the bytecode file and execute the instructions in it. If your program is error-free, a window will appear on the screen.



Four standard classes:

1.      JOptionPane

2.      String

3.      Date

4.      SimpleDateFormat


JOptionPane for Output

/*
 * Chapter 2 Sample program: Shows a Message Dialog
 * File: Ch2ShowMessageDialog.java
 */
importjavax.swing.*;
class Ch2ShowMessageDialog {
public static void main(String[] args){
JFramejFrame;
jFrame = new JFrame();
jFrame.setSize(400,300);
jFrame.setVisible(true);

JOptionPane.showMessageDialog(jFrame,"How are you?");
JOptionPane.showMessageDialog(null,"Good Bye");

    }
}




HELPFUL REMINDERS
The showMessageDialog method of JOptionPane is a class method. As such, there’s no need to create an instance of JOptionPane.

If you want to display multiple lines of text, we can use a special character sequence \n to separate the lines, as in
               
                JOptionPane.showMessageDialog(null, “one\ntwo\nthree”);

Which will result in the dialog
Quick Check
1.       Write Java statements to display a message dialog with the text I Love Java
2.       Write statements to display the following shopping list on a message dialog:
Shopping List:
                Apple
                Banana
                Lowfat Milk

String

/*
 * Chapter 2 Sample Program: Simple String Processing
 * file: Ch2StringProcessing.java
 */
importjavax.swing.*;
class Ch2StringProcessing2{
public static void main( String[] args){
        String text;
text = "Espresso";
JOptionPane.showMessageDialog(null, text.substring(2,7));

    }
}





E
S
P
R
E
S
S
O
0                              1                              2                    3                          4                        5                          6      7





/*
 * Chapter 2 Sample Program: Simple String Processing
 * file: Ch2StringProcessing.java
 */
importjavax.swing.*;
class Ch2StringProcessing {
public static void main( String[] args){
        String fullName,firstName,lastName,space;
fullName = new String("Decafe Latte");
space = new String(" ");
firstName= fullName.substring(0,fullName.indexOf(space));
lastName =  fullName.substring(fullName,indexOf(space) + 1, fullName.length());

JOptionPane.showMessageDialog(null,"Full Name:" + fullName);
JOptionPane.showMessageDialog(null, "First:" + firstName);
JOptionPane.showMessageDialog (null, "Last:" + lastName);
JOptionPane.showMessageDialog(null,"You last name has " + lastName.length() + "characters.");
    }

}