How to Print a Number Pyramid in Java

The following Java program prints a sequential number pyramid in Java. The output of the program is given below.

 

    1 
   2 3 
  4 5 6 
 7 8 9 10 
11 12 13 14 15 
 
/**
 * Prints number pyramid Java
 * @author jj
 */
public class NumberPyramid {
    public static void main(String[] args) {
        int rows = 5; // number of rows for pyramid
        for(int i=1;i<=rows;i++) {
            for(int k=rows-i;k>=1;k--) {
                System.out.print(" ");
            }
            for(int j=1;j<=i;j++) {                
                System.out.print(i*(i-1)/2+j+" ");
            }
            System.out.println();
        }
    }
}

Java Program to Find Repeated Words in a String

The following Java program prints repeated/duplicated words in a String. The program uses case insensitive comparison (For example, program assumes words CAT, cat and Cat etc. are all same). This algorithm is useful in text processing programs where word frequency calculations are needed.

The program first asks for the input string from the command line. Using the split function, this string is broken into individual words. We then add each word into a map checking whether the word already exists. Whenever we find a word that is repeated, we print the word.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// How to find repeated/duplicated words in a string using Java
public class DuplicateWords {
    
    public static void main(String[] args) {
        System.out.print("Enter string to analyse:");
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        
        // first let us split string into words
        String[] words = input.split(" ");
        
        // adds all words into a map
        // we also check whether the word is already in map!
        Map<String,String> wordMap = new HashMap<String,String>();
        for(int i=0;i<words.length;i++) {
            String word = words[i].toUpperCase(); // for case insensitive comparison
            if(wordMap.get(word)!=null) {
                // we found a duplicated word!
                System.out.println("Duplicated/Repeated word:"+word);
            }else {
                wordMap.put(word, word);
            }
        }
    }   
}

If a word is repeated more than once, it is printed multiple times. The following program fixes this by keeping track of printed words using another map.

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// How to find repeated/duplicated words in a string using Java
public class DuplicateWords2 {
    
    public static void main(String[] args) {
        System.out.print("Enter string to analyse:");
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        
        // first let us split string into words
        String[] words = input.split(" ");
        
        // adds all words into a map
        // we also check whether the word is already in map!
        Map<String,String> wordMap = new HashMap<String,String>();                
        Map<String,String> printedMap = new HashMap<String,String>();

        for(int i=0;i<words.length;i++) {
            String word = words[i].toUpperCase(); // for case insensitive comparison
            if(wordMap.get(word)!=null) {
                // we found a duplicated word!
                if(printedMap.get(word)==null) { // first check if it is printed already!
                    System.out.println("Duplicated/Repeated word:"+word);
                    printedMap.put(word, word); 
                }
            }else {
                wordMap.put(word, word);
            }
        }
    }
    
}

Area of a Circle in Java

The formula for calculating area of a circle is,

Area = PI * r * r, where PI is a constant and r is the radius of the circle.

The following sample Java program calculates area of a circle. The radius of the circle is taken as user input from command line. The default Java language package contains a Math class which the following program uses for the value of PI.

import java.util.Scanner;

/**
 * Java program to calculate area of a circle
 * @author jj
 */
public class AreaOfCircle {
    
    public static void main(String[] args) {
        System.out.print("Enter radius of circle: ");
        Scanner sn = new Scanner(System.in);
        Double radius = sn.nextDouble();
        
        Double area = Math.PI * radius * radius;        
        System.out.println("Area = "+area);
    }
}

Writing a Text File in Java

Java has plenty of classes for file manipulation. For simple text files which contains lines of text, the best classes to use are FileWriter and PrintWriter in java.io package. PrintWriter has the method println() which writes a string into the file followed by a new line. Also note that PrintWriter and FileWriter must be closed in that order for the data to be actually written in the file. If you do not close PrintWriter or FileWriter, you may find that the resulting file is empty. FileWriter may throw checked exception IOException in case of any runtime error.

The following program demonstrates how you can write a text file in Java.

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


/** Writing a text file Java.
 * 
 * @author jj
 */
public class WriteFile {
   
    public static void main(String[] args) {
        
        // data to write in file
        String data = "Hello World!";
        try {
            // Change this to a valid directory and file name in your system
            FileWriter fw = new FileWriter("/Volumes/ZEN/temp/test.txt");
            PrintWriter pw = new PrintWriter(fw);
            
            pw.println(data);
            
            pw.close();
            fw.close();
            
        }catch(IOException ex){
            System.out.println("Unable to write file!");
            ex.printStackTrace();
        }
        
    }
}

Splitting Strings in Java

One of the common string processing requirements in computer programs is to split a string into sub strings based on a delimiter. This can be easily achieved in Java using its rich String API. The split function in String class takes the delimiter as a parameter expressed in regular expression form.

The following Java program demonstrates the use of split function for splitting strings. Note that characters which has special meaning in regular expressions must be escaped using a slash (\) when passed as parameter to split function. Also note that an additional slash is required to escape slash in a Java string.

Please see this page on regular expressions for more details.

/**
 * Sample program to split strings in Java. The Java String API has a built-in 
 * split function which uses regular expressions for splitting strings.
 * 
 * 
 */
public class SplitString {
    
    public static void main(String[] args) {
        
        // Demo1 - splitting comma separated string
        String commaSeparatedCountries = "India,USA,Canada,Germany";
        String[]countries = commaSeparatedCountries.split(",");
        // print each country!
        for(int i=0;i<countries.length;i++) {
            System.out.println(countries[i]);
        }
        
        // Demo2 - Splitting a domain name into its subdomains
        // The character dot (.) has special meaning in regular expressions and 
        // hence must be escaped. Double slash is required to escape slash in Java 
        // string.
        String fullDomain = "www.blog.quickprogrammingtips.com";
        String[] domainParts = fullDomain.split("\\.");
        
        for(int i=0;i<domainParts.length;i++) {
            System.out.println(domainParts[i]);
        }
        
        
        // Demo3 - Splitting a string using regular expressions
        // In this example we want splitting on characters such as comma,dot or 
        // pipe. We use the bracket expression defined in regular expressions.
        // Only dot(.) requires escaping.
        String delimtedText = "data1,data2|data3.data4";
        String[] components = delimtedText.split("[,|\\.]");
        
        for(int i=0;i<components.length;i++) {
            System.out.println(components[i]);
        }   
    } 
}