Saturday, August 22, 2015

How to get input from user in java

This program tells you how to get input from user in a java program. We are using Scanner class to get input from user. This program firstly asks the user to enter a string and then the string is printed, then an integer and entered integer is also printed and finally a float and it is also printed on the screen. Scanner class is present in java.util package so we import this package in our program. We first create an object of Scanner class and then we use the methods of Scanner class. Consider the statement:

Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program below:-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
Java programming source code

import java.util.Scanner;
 
class GetInputFromUser
{
 public static void main(String args[])
 {
 int a;
 float b;
 String s;
 
 Scanner in = new Scanner(System.in);
 
 System.out.println("Enter a string");
 s = in.nextLine();
 System.out.println("You entered string "+s);
 
 System.out.println("Enter an integer");
 a = in.nextInt();
 System.out.println("You entered integer "+a);
 
 System.out.println("Enter a float");
 b = in.nextFloat();
 System.out.println("You entered float "+b); 
 }
}

Output of program:


There are other classes which can be used for getting input from user and you can also take input from other devices.

Java program to print multiplication table


This java program prints multiplication table of a number entered by the user using a for loop. You can modify it for while or do while loop for practice.

Java programming source code


import java.util.Scanner;
 
class MultiplicationTable
{
 public static void main(String args[])
 {
 int n, c;
 System.out.println("Enter an integer to print it's multiplication table");
 Scanner in = new Scanner(System.in);
 n = in.nextInt();
 System.out.println("Multiplication table of "+n+" is :-");
 
 for ( c = 1 ; c <= 10 ; c++ )
 System.out.println(n+"*"+c+" = "+(n*c));
 }
}

Output of program:



Using nested loops we can print tables of number between a given range say a to b, For example if the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:

import java.util.Scanner;
 
class Tables
{
 public static void main(String args[])
 {
 int a, b, c, d;
 
 System.out.println("Enter range of numbers to print their multiplication table");
 Scanner in = new Scanner(System.in);
 
 a = in.nextInt();
 b = in.nextInt();
 
 for (c = a; c <= b; c++) {
 System.out.println("Multiplication table of "+c);
 
 for (d = 1; d <= 10; d++) {
 System.out.println(c+"*"+d+" = "+(c*d));
 }
 }
 }
}

Friday, August 21, 2015

Java program to print alphabets


This program print alphabets on screen i.e a, b, c, ..., z. Here we print alphabets in lower case.

Java source code


class Alphabets
{
 public static void main(String args[])
 {
 char ch;
 
 for( ch = 'a' ; ch <= 'z' ; ch++ )
 System.out.println(ch);
 }
}

You can easily modify the above java program to print alphabets in upper case.

Output of program:


Printing alphabets using while loop (only body of main method is shown):
char c = 'a';
 
while (c <= 'z') {
 System.out.println(c);
 c++;
}

Using do while loop:
char c = 'A';
 
do {
 System.out.println(c);
 c++;
} while (c <= 'Z');

Java while loop

Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:

while (condition(s)) {
// Body of loop
}

1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.

2. You can test multiple conditions such as

while ( a > b && c != 0) {
 // Loop body
}

Loop body is executed till value of a is greater than value of b and c is not equal to zero.

3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable.
Java while loop example

Following program asks the user to input an integer and prints it until user enter 0 (zero).

import java.util.Scanner;
 
class WhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input an integer"); 
 
 while ((n = input.nextInt()) != 0) {
 System.out.println("You entered " + n);
 System.out.println("Input an integer");
 }
 
 System.out.println("Out of loop");
 }
}

Output of program:


Above program can be written in a more compact way as follows:

// Java while loop user input 
import java.util.Scanner;
 
class WhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input an integer"); 
 
 while ((n = input.nextInt()) != 0) {
 System.out.println("You entered " + n);
 System.out.println("Input an integer");
 }
 }
}

Java while loop break program


Here we write above program but uses break statement. The condition in while loop here is always true so we test the user input and if its is zero then we use break to exit or come out of the loop.

import java.util.Scanner;
 
class BreakWhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 
 while (true) {
 System.out.println("Input an integer");
 n = input.nextInt();
 
 if (n == 0) {
 break;
 }
 System.out.println("You entered " + n);
 }
 }
}

Java while loop break continue program


import java.util.Scanner;
 
class BreakContinueWhileLoop {
 public static void main(String[] args) {
 int n;
 
 Scanner input = new Scanner(System.in);
 
 while (true) {
 System.out.println("Input an integer");
 n = input.nextInt();
 
 if (n != 0) {
 System.out.println("You entered " + n);
 continue;
 }
 else {
 break;
 }
 }
 }
}

Whatever you can do with while loop can be done with for and do while loop.

Java for loop


Java for loop used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.

Java for loop syntax


for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
 // Statements to execute i.e. Body of for loop
}

You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.

// Infinite for loop
for (;;) {
 System.out.println("Java programmer");
}

You can terminate an infinite loop by pressing Ctrl+C.

Simple for loop example in Java


Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.

//Java for loop program
class ForLoop {
 public static void main(String[] args) {
 int c;
 
 for (c = 1; c <= 10; c++) {
 System.out.println(c);
 }
 }
}

Output of program:


Java for loop example to print stars in console


Following star pattern is printed
*
**
***
****
*****

class Stars {
 public static void main(String[] args) {
 int row, numberOfStars;
 
 for (row = 1; row <= 10; row++) {
 for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
 System.out.print("*");
 }
 System.out.println(); // Go to next line
 }
 }
}

Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.

Output of program: