Showing posts with label methods. Show all posts
Showing posts with label methods. Show all posts

Escaping HTML Special Characters method in Java

Description:

Source code for the Html Escape class, for escaping text on the fly, using Java.
The Html Escape tool for Java, escapes all characters, known to cause problems on Html pages.
The escaped result is compatible with pages encoded in ISO-8859-X and UTF-8.


The two main methods of the HtmlEscape class are:

escape(String)
Which escapes everything, including new line and returns the escaped result

escapeTextArea(String)
Which escapes everything, except new line, for use in textarea or wysiwyg editors.

Code:

package net.htmlescape; 

/** 
* HtmlEscape in Java, which is compatible with utf-8 
* @author Ulrich Jensen, http://www.htmlescape.net 
* Feel free to get inspired, use or steal this code 
* and use it in your own projects. 
* License: 
* You have the right to use this code in your own 
* project or publish it on your own website. 
* If you are going to use this code, please include 
* the author lines. Use this code at your own risk. 
* The author does not warrant or assume any legal 
* liability or responsibility for the accuracy, 
* completeness or usefulness of this program code. 
*/ 

public class HtmlEscape { 

  private static char[] hex={'0','1','2','3','4','5','6',
                        '7','8','9','a','b','c','d','e','f'}; 

  /** 
   * Method for html escaping a String, for use in a textarea 
   * @param original The String to escape 
   * @return The escaped String 
   */ 
  public static String escapeTextArea(String original) 
  { 
    return escapeSpecial(escapeTags(original));     
  } 
   
  /** 
   * Normal escape function, for Html escaping Strings 
   * @param original The original String 
   * @return The escape String 
   */ 
  public static String escape(String original) 
  { 
    return escapeSpecial(escapeBr(escapeTags(original))); 
  } 
   
  public static String escapeTags(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
      boolean found=true; 
      switch(chars[i]) 
      { 
        case 60:out.append("&lt;"); break; //< 
        case 62:out.append("&gt;"); break; //> 
        case 34:out.append("&quot;"); break; //" 
        default:found=false;break; 
      } 
      if(!found) out.append(chars[i]); 
       
    } 
    return out.toString(); 
     
  } 

  public static String escapeBr(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
      boolean found=true; 
      switch(chars[i]) 
      { 
        case '\n': out.append("<br/>"); break; //newline 
        case '\r': break; 
        default:found=false;break; 
      } 
      if(!found) out.append(chars[i]); 
       
    } 
    return out.toString(); 
  } 
   
  public static String escapeSpecial(String original) 
  { 
    if(original==null) return ""; 
    StringBuffer out=new StringBuffer(""); 
    char[] chars=original.toCharArray(); 
    for(int i=0;i<chars.length;i++) 
    { 
        boolean found=true; 
      switch(chars[i]) { 
        case 38:out.append("&amp;"); break; //& 
        case 198:out.append("&AElig;"); break; //Æ 
        case 193:out.append("&Aacute;"); break; //Á 
        case 194:out.append("&Acirc;"); break; // 
        case 192:out.append("&Agrave;"); break; //À 
        case 197:out.append("&Aring;"); break; //Å 
        case 195:out.append("&Atilde;"); break; //à
        case 196:out.append("&Auml;"); break; //Ä 
        case 199:out.append("&Ccedil;"); break; //Ç 
        case 208:out.append("&ETH;"); break; //Р
        case 201:out.append("&Eacute;"); break; //É 
        case 202:out.append("&Ecirc;"); break; //Ê 
        case 200:out.append("&Egrave;"); break; //È 
        case 203:out.append("&Euml;"); break; //Ë 
        case 205:out.append("&Iacute;"); break; //Í 
        case 206:out.append("&Icirc;"); break; //Π
        case 204:out.append("&Igrave;"); break; //Ì 
        case 207:out.append("&Iuml;"); break; //Ï 
        case 209:out.append("&Ntilde;"); break; //Ñ 
        case 211:out.append("&Oacute;"); break; //Ó 
        case 212:out.append("&Ocirc;"); break; //Ô 
        case 210:out.append("&Ograve;"); break; //Ò 
        case 216:out.append("&Oslash;"); break; //Ø 
        case 213:out.append("&Otilde;"); break; //Õ 
        case 214:out.append("&Ouml;"); break; //Ö 
        case 222:out.append("&THORN;"); break; //Þ 
        case 218:out.append("&Uacute;"); break; //Ú 
        case 219:out.append("&Ucirc;"); break; //Û 
        case 217:out.append("&Ugrave;"); break; //Ù 
        case 220:out.append("&Uuml;"); break; //Ü 
        case 221:out.append("&Yacute;"); break; //Ý 
        case 225:out.append("&aacute;"); break; //á 
        case 226:out.append("&acirc;"); break; //â 
        case 230:out.append("&aelig;"); break; //æ 
        case 224:out.append("&agrave;"); break; //à 
        case 229:out.append("&aring;"); break; //å 
        case 227:out.append("&atilde;"); break; //ã 
        case 228:out.append("&auml;"); break; //ä 
        case 231:out.append("&ccedil;"); break; //ç 
        case 233:out.append("&eacute;"); break; //é 
        case 234:out.append("&ecirc;"); break; //ê 
        case 232:out.append("&egrave;"); break; //è 
        case 240:out.append("&eth;"); break; //ð 
        case 235:out.append("&euml;"); break; //ë 
        case 237:out.append("&iacute;"); break; //í 
        case 238:out.append("&icirc;"); break; //î 
        case 236:out.append("&igrave;"); break; //ì 
        case 239:out.append("&iuml;"); break; //ï 
        case 241:out.append("&ntilde;"); break; //ñ 
        case 243:out.append("&oacute;"); break; //ó 
        case 244:out.append("&ocirc;"); break; //ô 
        case 242:out.append("&ograve;"); break; //ò 
        case 248:out.append("&oslash;"); break; //ø 
        case 245:out.append("&otilde;"); break; //õ 
        case 246:out.append("&ouml;"); break; //ö 
        case 223:out.append("&szlig;"); break; //ß 
        case 254:out.append("&thorn;"); break; //þ 
        case 250:out.append("&uacute;"); break; //ú 
        case 251:out.append("&ucirc;"); break; //û 
        case 249:out.append("&ugrave;"); break; //ù 
        case 252:out.append("&uuml;"); break; //ü 
        case 253:out.append("&yacute;"); break; //ý 
        case 255:out.append("&yuml;"); break; //ÿ 
        case 162:out.append("&cent;"); break; //¢ 
        default: 
          found=false; 
          break; 
      } 
      if(!found) 
      { 
        if(chars[i]>127) { 
          char c=chars[i]; 
          int a4=c%16; 
          c=(char) (c/16); 
          int a3=c%16; 
          c=(char) (c/16); 
          int a2=c%16; 
          c=(char) (c/16); 
          int a1=c%16; 
          out.append("&#x"+hex[a1]+hex[a2]+
                              hex[a3]+hex[a4]+";");     
        } 
        else 
        { 
          out.append(chars[i]); 
        } 
      } 
    }   
    return out.toString(); 
  } 
   
} 
Read More

Creating a Real Calendar in Java

Problem:

Write a program that prompt the user to enter the year and the month and later print the calendar for the month of the year. You are free to solve the problem in your own way, or you could follow with the tips; as long as you get same output. To print a body, first pad some space before the start day and then print the lines for every week, as shown in the output.
The program does validate user input. For instance, if the user enters either a month not in the range between 1 and 12 or a year before 1800, the program would display an erroneous calendar. To avoid this error, add an if statement to check the input before printing the calendar.

The isLeapYear(int year) method can be implemented using the following code: return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));

Use the following facts to implement getTotalNumberOfDaysInMonth(int year, int month):
1) January, March, May, July, August, October, and December have thirty-one days.
2) April, June, September, and November have thirty days.
3) February has twenty-eight days during a regular year and twenty-nine days during a leap year. A regular year, therefore, has 365 days, whereas a leap year has 366 days.

To implement getTotalNumberOfDays(int year, int month), you need to compute the total number of days (totalNumberOfDays) between January 1, 1800 and the first day of the calendar month. You could find the total number of days between the year 1800 and the calendar year and then figure out the total number of days prior to the calendar month in the calendar year. The sum of these two totals is totalNumberOfDays.

To print a body, first pad some space before the start day and then print the lines for every week, as shown for December 2012. Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as collections of concise methods are easier to write, debug, maintain, and modify than would otherwise be the case. This writing style also promotes method reusability.

When implementing a large program, use the top-down or bottom-up approach. Do not write the entire program at once. This approach seems to take more time for coding (because you are repeatedly compiling and running the program), but it actually saves time and makes debugging easier.

This program prints calendars for a month but could easily be modified to print calendars for a whole year. Although it can only print months after January 1800, it could be modified to trace the day of a month before 1800.


Output:

Enter full year (e.g., 2001): 2012
Enter month in number between 1 and 12: 12
December 2012
–––––––––––––––––––––––––––––
Sun Mon Tue Wed Thu Fri Sat
1
2   3   4   5   6   7   8
9   10  11  12  13  14  15
16  17  18  19  20  21  22
23  24  25  26  27  28  29
30  31


Solution:

 import java.util.Scanner;

    public class PrintCalendar {

      /** Main method */

      public static void main(String[] args) {
      Scanner scan = new Scanner (System.in);

      //Prompt the user to enter year
      System.out.print("Enter full year (e.g., 2001): ");
      int year = scan.nextInt();

      // Prompt the user to enter month
      System.out.print("Enter month in number between 1 and 12: ");
      int month = scan.nextInt();

      // Print calendar for the month of the year
       if (month < 1 || month > 12 || year < 1980)
        System.out.println("Wrong input!");
        else
            printMonth(year, month);

    }
     /** Print the calendar for a month in a year */

      static void printMonth(int year, int month) {

      //Print the headings of the calendar
       printMonthTitle(year, month);

      //Print the body of the calendar
       printMonthBody(year, month);
     }

     /** Print the month title, e.g., May, 1999 */

     static void printMonthTitle(int year, int month) {

     System.out.println("         " + getMonthName(month) + " " + year);
     System.out.println("–––––––––––––––––––––––––––––");
     System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

     }

     /** Get the English name for the month */
     static String getMonthName(int month) {
       String monthName = null;
       switch (month) {
         case 1: monthName = "January"; break;
         case 2: monthName = "February"; break;
         case 3: monthName = "March"; break;
         case 4: monthName = "April"; break;
         case 5: monthName = "May"; break;
         case 6: monthName = "June"; break;
         case 7: monthName = "July"; break;
         case 8: monthName = "August"; break;
         case 9: monthName = "September"; break;
         case 10: monthName = "October"; break;
         case 11: monthName = "November"; break;
         case 12: monthName = "December";
       }
       return monthName;
     }

     /** Print month body */
     static void printMonthBody(int year, int month) {

       // Get start day of the week for the first date in the month
       int startDay = getStartDay(year, month);

       // Get number of days in the month
       int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

       // Pad space before the first day of the month
       int i = 0;
       for (i = 0; i < startDay; i++)
         System.out.print("    ");
       for (i = 1; i <= numberOfDaysInMonth; i++) {
         if (i < 10)
           System.out.print("   " + i);
         else
           System.out.print("  " + i);
         if ((i + startDay) % 7 == 0)
           System.out.println();
       }
       System.out.println();
     }

     /** Get the start day of the first day in a month */

    static int getStartDay(int year, int month) {

       //Get total number of days since 1/1/1800
       int startDay1800 = 3;
       int totalNumberOfDays = getTotalNumberOfDays(year, month);

       //Return the start day
       return (totalNumberOfDays + startDay1800) % 7;
     }

     /** Get the total number of days since January 1, 1800 */

     static int getTotalNumberOfDays(int year, int month) {
      int total = 0;

      //Get the total days from 1800 to year - 1
      for (int i = 1800; i < year; i++)
      if (isLeapYear(i))
         total = total + 366;
       else
         total = total + 365;
 
       //Add days from January to the month prior to the calendar month
       for (int i = 1; i < month; i++)
         total = total + getNumberOfDaysInMonth(year, i);
 
       return total;
     }
 
     /** Get the number of days in a month */

     static int getNumberOfDaysInMonth(int year, int month) {
       if (month == 1 || month == 3 || month == 5 || month == 7 ||
         month == 8 || month == 10 || month == 12)
         return 31;
 
       if (month == 4 || month == 6 || month == 9 || month == 11)
         return 30;
 
       if (month == 2) return isLeapYear(year) ? 29 : 28;
 
       return 0; // If month is incorrect
     }
 
     /** Determine if it is a leap year */
     static boolean isLeapYear(int year) {
       return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
     }
 }
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact