URLTest.java Demonstrates try/catch blocks. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
 // Further simplified getURL method. 
 
 public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.n" +
                        		 "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Can skip return(null) now
    } finally {
      return(url);
    }
  }
import java.net.*; // For URL, MalformedURLException
import java.io.*;  // For BufferedReader

/** A small class to demonstrate try/catch blocks.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class URLTest {
  public static void main(String[] args) {
    URLTest test = new URLTest();
    test.getURL();
    test.printURL();
  }

  private URL url = null;

  /** Read a string from user and create a URL from it. If
   *  reading fails, give up and report error. If reading
   *  succeeds but URL is illegal, try again.
   */

  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString;
    try {
      urlString = in.readLine();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump.
      return(null);
    }
    try {
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.n" +
                         "Try again.");
      getURL();
    }
    return(url);
  }

  /** Print info on URL. */

  public void printURL() {
    if (url == null) {
      System.out.println("No URL.");
    } else {
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
      if (protocol.equals("http") && (port == -1)) {
        port = 80;
      }
      String file = url.getFile();
      System.out.println("Protocol: " + protocol +
                         "nHost: " + host +
                         "nPort: " + port +
                         "nFile: " + file);
    }
  }
}
/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
  // Simplified getURL method.
  
  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.n" +
                       			 "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump
      return(null);
    }
    return(url);
  }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10218
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Factorial.java Computes an exact factorial, n!, using a BigInteger #Programming Code Examples #Java/J2EE/J2ME #Basic Java

import java.math.BigInteger;

/** Computes an exact factorial, using a BigInteger.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Factorial {
  public static void main(String[] args) {
    for(int i=1; i< =256; i*=2) {
      System.out.println(i + "!=" + factorial(i));
    }
  }

  public static BigInteger factorial(int n) {
    if (n <= 1) {
      return(new BigInteger("1"));
    } else {
      BigInteger bigN = new BigInteger(String.valueOf(n));
      return(bigN.multiply(factorial(n - 1)));
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10217
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ExecTest.java illustrates use of the Exec class. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** A test of the Exec class.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class ExecTest {
  public static void main(String[] args) {
    // Note: no trailing "&" -- special shell chars not
    // understood, since no shell started. Besides, exec
    // doesn?t wait, so the program continues along even
    // before Netscape pops up.
    Exec.exec("/usr/local/bin/netscape");

    // Run commands, printing results.
    Exec.execPrint("/usr/bin/ls");
    Exec.execPrint("/usr/bin/cat Test.java");

    // Don?t print results, but wait until this finishes.
    Exec.execWait("/usr/java1.3/bin/javac Test.java");

    // Now Test.class should exist.
    Exec.execPrint("/usr/bin/ls");
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10216
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Exec.java Provides static methods for running external processes from applications. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

import java.io.*;

/** A class that eases the pain of running external processes
 *  from applications. Lets you run a program three ways:
 *  
    *
  1. exec: Execute the command, returning * immediately even if the command is still running. * This would be appropriate for printing a file. *
  2. execWait: Execute the command, but don?t * return until the command finishes. This would be * appropriate for sequential commands where the first * depends on the second having finished (e.g., * javac followed by java). *
  3. execPrint: Execute the command and print the * output. This would be appropriate for the Unix * command ls. *
* Note that the PATH is not taken into account, so you must * specify the full pathname to the command, and shell * built-in commands will not work. For instance, on Unix the * above three examples might look like: *
    *
  1. Exec.exec("/usr/ucb/lpr Some-File");

    *

  2. Exec.execWait("/usr/local/bin/javac Foo.java");
     *        Exec.execWait("/usr/local/bin/java Foo");

    *

  3. Exec.execPrint("/usr/bin/ls -al");

    *

*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class Exec {

private static boolean verbose = true;

/** Determines if the Exec class should print which commands
* are being executed, and prints error messages if a problem
* is found. Default is true.
*
* @param verboseFlag true: print messages, false: don?t.
*/

public static void setVerbose(boolean verboseFlag) {
verbose = verboseFlag;
}

/** Will Exec print status messages? */

public static boolean getVerbose() {
return(verbose);
}

/** Starts a process to execute the command. Returns
* immediately, even if the new process is still running.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins (e.g., "cd") or shell
* meta-chars (e.g. ">") are allowed.
* @return false if a problem is known to occur, but since
* this returns immediately, problems aren?t usually found
* in time. Returns true otherwise.
*/

public static boolean exec(String command) {
return(exec(command, false, false));
}

/** Starts a process to execute the command. Waits for the
* process to finish before returning.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins or shell metachars are
* allowed.
* @return false if a problem is known to occur, either due
* to an exception or from the subprocess returning a
* nonzero value. Returns true otherwise.
*/

public static boolean execWait(String command) {
return(exec(command, false, true));
}

/** Starts a process to execute the command. Prints any output
* the command produces.
*
* @param command The full pathname of the command to
* be executed. No shell built-ins or shell meta-chars are
* allowed.
* @return false if a problem is known to occur, either due
* to an exception or from the subprocess returning a
* nonzero value. Returns true otherwise.
*/

public static boolean execPrint(String command) {
return(exec(command, true, false));
}

/** This creates a Process object via Runtime.getRuntime.exec()
* Depending on the flags, it may call waitFor on the process
* to avoid continuing until the process terminates, and open
* an input stream from the process to read the results.
*/

private static boolean exec(String command,
boolean printResults,
boolean wait) {
if (verbose) {
printSeparator();
System.out.println("Executing '" + command + "'.");
}
try {
// Start running command, returning immediately.
Process p = Runtime.getRuntime().exec(command);

// Print the output. Since we read until there is no more
// input, this causes us to wait until the process is
// completed.
if(printResults) {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = null;
try {
while ((s = buffer.readLine()) != null) {
System.out.println("Output: " + s);
}
buffer.close();
if (p.exitValue() != 0) {
if (verbose) {
printError(command + " -- p.exitValue() != 0");
}
return(false);
}
} catch (Exception e) {
// Ignore read errors; they mean the process is done.
}

// If not printing the results, then we should call waitFor
// to stop until the process is completed.
} else if (wait) {
try {
System.out.println(" ");
int returnVal = p.waitFor();
if (returnVal != 0) {
if (verbose) {
printError(command);
}
return(false);
}
} catch (Exception e) {
if (verbose) {
printError(command, e);
}
return(false);
}
}
} catch (Exception e) {
if (verbose) {
printError(command, e);
}
return(false);
}
return(true);
}

private static void printError(String command,
Exception e) {
System.out.println("Error doing exec(" + command + "): " +
e.getMessage());
System.out.println("Did you specify the full " +
"pathname?");
}

private static void printError(String command) {
System.out.println("Error executing ?" + command + "?.");
}

private static void printSeparator() {
System.out.println
("==============================================");
}
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10215
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** Simulating dropping a ball from the top of the Washington
 *  Monument. The program outputs the height of the ball each
 *  second until the ball hits the ground.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class DropBall {
  public static void main(String[] args) {
    int time = 0;
    double start = 550.0, drop = 0.0;
    double height = start;
    while (height > 0) {
      System.out.println("After " + time +
                   (time==1 ? " second, " : " seconds,") +
                   "the ball is at " + height + " feet.");
      time++;
      drop = freeFall(time);
      height = start - drop;
    }
    System.out.println("Before " + time + " seconds could " +
                       "expire, the ball hit the ground!");
  }

  /** Calculate the distance in feet for an object in
   *  free fall.
   */

  public static double freeFall (float time) {
    // Gravitational constant is 32 feet per second squared
    return(16.0 * time * time); // 1/2 gt^2
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10214
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Creates three radio buttons and illustrates handling #Programming Code Examples #Java/J2EE/J2ME #Basic Swing

JRadioButtonTest.java Creates three radio buttons and illustrates handling ItemEvents in response to selecting a radio button. 
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/** 
 */

public class JRadioButtonTest extends JPanel
                              implements ItemListener {

  public JRadioButtonTest() {
   
    String[] labels = {"Java Swing","Java Servlets",
                       "JavaServer Pages"};
    JRadioButton[] buttons = new JRadioButton[3];
    ButtonGroup group = new  ButtonGroup();

    for(int i=0; i<buttons .length; i++) {
      buttons[i] = new JRadioButton(labels[i]);
      buttons[i].setContentAreaFilled(false);
      buttons[i].addItemListener(this);
      group.add(buttons[i]);
      add(buttons[i]);
    }
  }

  public void itemStateChanged(ItemEvent event) {
    JRadioButton radiobutton = (JRadioButton)event.getItem();

    if (event.getStateChange() == ItemEvent.SELECTED) {
      System.out.println(radiobutton.getText() + " selected.");
    } else {
      System.out.println(radiobutton.getText() + " deselected.");
    }
  }

  public static void main(String[] args) {
    JPanel panel = new JRadioButtonTest();
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(panel, 400, 75);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10318
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Swing
Tags:Java/J2EE/J2MEBasic Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Technical and Vocational Institute Summary Report

Technical and Vocational Institute Summary Report
Education levelManagementInstituteTeacherStudent
TotalFemaleTotalFemalTotalFemale
01 – POLYTECHNIC INSTITUTEPRIVATE35712475986859461887
PUBLIC57313891652717315960
02 -TECHNICAL SCHOOL AND COLLEGEPRIVATE845101622216257
PUBLIC370440651165183
03 – TEXTILE (Vocational Institute)PUBLIC27015634141
04 – TEXTILE TRAINING CENTERPRIVATE7401832052942263
PUBLIC2245929249292339
05 – AGRICULTURE TRAINING INSTITUTEPRIVATE5705027715960
PUBLIC809421
06 – TEXTILE INSTITUTEPRIVATE120135315023
PUBLIC10241
07 – NATIONAL SKILLPRIVATE1291119854572
PUBLIC103913
08 – H.S.C(Vocational Independent)PRIVATE1030
09 – H.S.C (B.M Independent)PRIVATE60061580912281607640
10 – SURVEY INSTITUTEPRIVATE1091
PUBLIC1050
11 – GRAPHIC ARTSPUBLIC10133
12 – S.S.C(Vocational Independent)PRIVATE1431177817213456
13 – GLASS AND CERAMICSPUBLIC10152
15 – HEALTH TECHNOLOGYPRIVATE53016938
PUBLIC30
17 – OTHERSPRIVATE1157112924437051217
PUBLIC2514985826471107
18 – DIPLOMA IN FISHERIESPRIVATE40
Total18141051754933046517830416

Simple example illustrating the use of check boxes #Programming Code Examples #Java/J2EE/J2ME #Basic Swing

JCheckBoxTest.java Simple example illustrating the use of check boxes. 
import javax.swing.*; 
import java.awt.event.*;

 */

public class JCheckBoxTest extends JPanel 
                           implements ItemListener, 
                                      ActionListener{
  JCheckBox checkBox1, checkBox2;
   
  public JCheckBoxTest() {
    checkBox1 = new JCheckBox("Java Servlets");
    checkBox2 = new JCheckBox("JavaServer Pages");
    checkBox1.setContentAreaFilled(false);
    checkBox2.setContentAreaFilled(false);
   
    checkBox1.addItemListener(this);
    checkBox2.addActionListener(this);
      
    add(checkBox1);
    add(checkBox2);
  }
   
  public void actionPerformed(ActionEvent event) {
    System.out.println("JavaServer Pages selected: " + 
                        checkBox2.isSelected());
  }
   
  public void itemStateChanged(ItemEvent event) {
    JCheckBox checkbox = (JCheckBox)event.getItem();
      
    if (event.getStateChange() == ItemEvent.SELECTED) {
      System.out.println(checkbox.getText() + " selected.");
    } else {
      System.out.println(checkbox.getText() + " deselected.");
    }
  }  
   
  public static void main(String[] args) {
    JPanel panel = new JCheckBoxTest();
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(panel, 300, 75);
  }   
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10317
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Swing
Tags:Java/J2EE/J2MEBasic Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Simple button that the user can select to load the entered URL. #Programming Code Examples #Java/J2EE/J2ME #Basic Swing

JIconButton.java A simple button that the user can select to load the entered URL. 
import javax.swing.*;

/** A regular JButton created with an ImageIcon and with borders
 *  and content areas turned off.
 *
  */

public class JIconButton extends JButton {
  public JIconButton(String file) {
    super(new ImageIcon(file));
    setContentAreaFilled(false);
    setBorderPainted(false);
    setFocusPainted(false);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10316
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Swing
Tags:Java/J2EE/J2MEBasic Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Basic tool bar for holding multiple buttons. #Programming Code Examples #Java/J2EE/J2ME #Basic Swing

BrowserToolBar.java A basic tool bar for holding multiple buttons. 
import java.awt.*;
import javax.swing.*;

/** Part of a small example showing basic use of JToolBar.
 *  Creates a small dockable toolbar that is supposed to look
 *  vaguely like one that might come with a Web browser.
 *  Makes use of ToolBarButton, a small extension of JButton
 *  that shrinks the margins around the icon and puts text 
 *  label, if any, below the icon. 
 *
  */
 
public class BrowserToolBar extends JToolBar {
  public BrowserToolBar() { 
    String[] imageFiles =
      { "Left.gif", "Right.gif", "RotCCUp.gif",
        "TrafficRed.gif", "Home.gif", "Print.gif", "Help.gif" };
    String[] toolbarLabels =
      { "Back", "Forward", "Reload", "Stop", 
        "Home", "Print", "Help" };
    Insets margins = new Insets(0, 0, 0, 0);
    for(int i=0; i<toolbarlabels .length; i++) {
      ToolBarButton button =
        new ToolBarButton("images/" + imageFiles[i]);
      button.setToolTipText(toolbarLabels[i]);
      button.setMargin(margins);
      add(button);
    }
  }

  public void setTextLabels(boolean labelsAreEnabled) {
    Component c;
    int i = 0;
    while((c = getComponentAtIndex(i++)) != null) {
      ToolBarButton button = (ToolBarButton)c;
      if (labelsAreEnabled) {
        button.setText(button.getToolTipText());
      } else {
        button.setText(null);
      }
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10314
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Swing
Tags:Java/J2EE/J2MEBasic Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada