Adding two numbers is one of the first programming problems given when someone is learning a new programming language. This program enables the programmer to focus on the language syntax since the algorithm for addition is trivial. It also demonstrates use of input/output, program structure, built-in utility libraries and basic language features like statements, comments and classes.
Java Program for Adding Two Numbers
The following program asks the user to enter two numbers separated by a space. It then outputs the sum of the numbers on the console.
// Adding two numbers in Java
import java.util.Scanner;
public class AddNumbers {
public static void main(String[] args) {
System.out.print("Enter two numbers separated by a space: ");
Scanner scanner = new Scanner(System.in);
int first = scanner.nextInt();
int second = scanner.nextInt();
int sum = first + second;
System.out.println("Sum of "+first+" and "+second +" is "+sum);
}
}
Posted in Java | Comments Off on Adding Two Numbers in Java
Finding number of a words in a String is a common problem in text processing. The Java string API and regular expression support in Java makes it a trivial problem.
Finding Word Count of a String in Java
The following Java program uses split() method and regular expressions to find the number of words in a string. Split() method can split a string into an array of strings. The splitting is done at substrings which matches the regular expression passed to the split() method. Here we pass a regular expression to match one or more spaces. We also print the individual words after printing the word count.
// Java program to find word count of a string
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class WordCount {
public static void main(String[] args) throws IOException {
System.out.print("Please enter a string: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String string = reader.readLine();
String[] words = string.split("\\s+"); // match one or more spaces
System.out.println("\""+string+"\""+" has "+words.length+" words");
System.out.println("The words are, ");
for(int i =0;i<words.length;i++) {
System.out.println(words[i]);
}
}
}
The above examples works even with strings which contain multiple consecutive spaces. For example, the string "This is a test" returns a count of 4. That is the beauty of regular expressions!
Posted in Java | Comments Off on Find Number of Words in a String in Java
One of the common text processing requirements is to remove a specific substring from a given string. For example, let us assume we have string "1,2,3,4,5" and we want to remove "3," from it to get the new string "1,2,4,5". The following Java program demonstrates how this can be achieved.
Java Program to Remove a Substring from a String
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
The key method here is replace(). This can be called on a string to replace the first parameter with the second parameter. When the second parameter is a blank string, it effectively deletes the substring from the main string.
Posted in Java | Comments Off on Removing a String from a String in Java
Definition of Triangular Number
Triangular number of a natural number n is the sum of all natural numbers from 1 to n. For example, Triangular number of 5 = 1 + 2 + 3 + 4 + 5 = 15. Mathematically,

It is known as triangular numbers since it is the total number of dots in a triangle with n dots on a side. For example, Triangular number of 5 can be represented in the following triangle,

Finding Triangular Number of a Number in Java
The following Java program finds the triangular number of a given number. It uses a simple loop to find the sum,
/* Printing Triangular number for a number in Java */
public class TriangularNumber {
public static void main(String[] args) {
int number = 6;
int triangular = 0;
for(int i = 1;i<=6;i++) {
triangular = triangular + i;
}
System.out.println("Triangular Number for "+number+" is "+triangular);
}
}
Finding Triangular Numbers of a Range of Numbers
The following Java program finds triangular numbers for a range of natural numbers,
/* Printing Triangular number for a range of numbers in Java */
public class TriangularNumbers {
public static void main(String[] args) {
int starting_number = 1;
int ending_number = 10;
System.out.println("List of Triangular Numbers ");
for (int i = starting_number; i <= ending_number; i++) {
int triangular = 0;
for (int j = 1; j <= i; j++) {
triangular = triangular + j;
}
System.out.println(i + " = " + triangular);
}
}
}
Another way of calculating Triangular number is to use the following formula,
Triangular number of n = (n*(n+1))/2.
/* Printing Triangular number for a number in Java using n*(n+1)/2 formula */
public class AlternateTriangularNumber {
public static void main(String[] args) {
int number = 9;
int triangular = number * (number+1)/2;
System.out.println("Triangular Number for "+number+" is "+triangular);
}
}
Posted in Java | Comments Off on Finding Triangular Numbers in Java
Pascal's triangle is a set of numbers arranged in the form of a triangle. Each number in a row is the sum of the left number and right number on the above row. If a number is missing in the above row, it is assumed to be 0. The first row starts with number 1. The following is a Pascal triangle with 5 rows,
|
|
|
|
1 |
|
|
|
|
|
|
|
1 |
|
1 |
|
|
|
|
|
1 |
|
2 |
|
1 |
|
|
|
1 |
|
3 |
|
3 |
|
1 |
|
| 1 |
|
4 |
|
6 |
|
4 |
|
1 |
The triangle is named after the French mathematician Blaise Pascal who organized detailed information on the triangle in a book. However this triangle was known in many ancient civilizations.
Pascal's triangle has a number of unique properties,
- The sum of numbers in each row is twice the sum of numbers in the above row
- The diagonals adjacent to the border diagonals contains natural numbers in order
Generate Pascal's Triangle in Java
The following Java program prints Pascal's triangle with 10 rows.
/* Program to print pascal triangle for 10 rows in java */
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Note the formatting commands used above to create a nicely formatted triangle. %4d instructs the formatter to print the number within 4 spaces. We choose 4 since we know the maximum number of digits in the largest number of a Pascal triangle with 10 rows is 3 digits.
The following program prints a Pascal's triangle when the number of rows are given as a parameter,
/* Program to print pascal triangle for 10 rows in java */
public class PascalTriangle {
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
for(int i =0;i<rows;i++) {
int number = 1;
System.out.format("%"+(rows-i)*2+"s","");
for(int j=0;j<=i;j++) {
System.out.format("%4d",number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Posted in Java | Comments Off on Program to Print Pascal Triangle in Java