Showing posts with label Java Programming. Show all posts
Showing posts with label Java Programming. Show all posts

Saturday, January 5, 2013

Implement a Java method that finds two neighbouring numbers in an array with the smallest distance to each other.



Implement a Java function that finds two neighbouring numbers in an array with the smallest distance to each other. The function should return the index of the first number.

In the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2). The function should return the index 3 (of number 1).

class LangFund3{
    static void smallestDistance(int [] array){
   
        int smallest = Math.abs(array[0]-array[1]);
        int index = 0;
        for(int i=1; i<array.length-1; i++){
            int value = Math.abs(array[i]-array[i+1]);
            if(value< smallest){
            smallest= value;
            index = i;
            }
               
        }
        System.out.println(smallest);
        System.out.println(index);   
           
    }
    public static void main(String [] args){
        int []arr= new int[]{4,8,6,1,2,9,4};
        smallestDistance(arr);
    }
}

How to find the largest and smallest number from a given Array using Java?

Find the largest and smallest number from a given array.

This java example shows how to find the largest and smallest number in an array.

        public class FindLargestSmallestNumber {
    
            public static void main(String[] args) {
                  
                    //array of 10 numbers
                    int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
                  
                    //assign first element of an array to largest and smallest
                    int smallest = numbers[0];
                    int largetst = numbers[0];
                  
                    for(int i=1; i< numbers.length; i++)
                    {
                            if(numbers[i] > largetst)
                                    largetst = numbers[i];
                            else if (numbers[i] < smallest)
                                    smallest = numbers[i];
                          
                    }
                  
                    System.out.println("Largest Number is : " + largetst);
                    System.out.println("Smallest Number is : " + smallest);
            }
    }

NumberFormatException and Exception hierarchy.

NumberFormatException and Exception hierarchy.
When we catch an exception with catch clause, we should catch exception from narrow to wide. Otherwise compiler will give a compilation error.
Here is a simple example to illustrate the NumberFormatException and usage of Exception hierarchy.

class NumberFormat{
    void throwExcep(){
        String s=null;
        int [] val={1,2,3,4,5};
        String ss="ABCD";
       
        try{
        int i=Integer.parseInt(ss);
        }
        catch(NumberFormatException np){
            System.out.println("NumberFormat");
       
        }
        catch(ArrayIndexOutOfBoundsException ae){
            System.out.println("ArrayIndexOutOfBounds");
        }
        catch(Exception e){
            System.out.println("Exception");
        }               
   
    }
    public static void main(String args[]){
        NumberFormat nf= new NumberFormat();
        nf.throwExcep();
    }
}

How to through and catch a NullPointerException in Java?

Simple example to show how to through and catch a NullPointerException in Java.

class NullPointer{
    public static void main(String args[]){
        String s=null;

            try{
                System.out.println(s.length());
            }
            catch(NullPointerException e){
                System.out.println("Null Pointer Exception caught by code");
            }
    }
}

How to validate a Social Security Number(SSN) using Java.

How to validate a SSN Number using Java?

SSNValidator class.

import java.util.regex.*;
class SSNValidator{
     public static void isValidSSN(String ssn) throws Exception{
 
        //Initialize reg expression for SSN.
        String expression = "^\\d{3}[- ]\\d{2}[- ]\\d{4}$";
        CharSequence inputStr = ssn;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);   
       
            if(matcher.matches()){
            System.out.println("Correct SNN Number");
            }
            else{
                throw new MyException(ssn);
            }           
    }
    public static void main(String args[])throws Exception{   
                String cmd="";
                try{
                     cmd=args[0];
                    }
                    catch(ArrayIndexOutOfBoundsException ae){
                    System.out.println("You shoud input your SSN number");
                    }
                isValidSSN(cmd);               
    }
}

Creating my own Exception class by extending Exception class.
class MyException extends Exception{
    private String s="";
    MyException(String val){
        this.s=val;
   
    }
      public String toString(){
        return "SSN number you were enter" + " " +s+" is not valid. "+ "please try again with correct format as given here. Ex:123-44-5678";
    }
}
  
How to run?
  1. Copy both java sources into one folder.
  2. Open cmd and navigate to that folder.
  3. Compile  main class(SSNValidator). 
  4. Then run with the SSN number. Ex(java SSNValidator 123-67-7890).
Meaning of Regex expression:
        "^\\d{3}[- ]\\d{2}[- ]\\d{4}$";
        ^\\d{3}:  Starts with three numeric digits.
        [- ]:  Followed by an "-"
        \\d{2}: Two numeric digits after the "-"
        [- ]:  contain an second "-" character.
       \\d{4}: ends with four numeric digits.
Above Regex format accepts only following format "xxx-xx-xxxx".
If you would like to change the Regex expression to accept 9 digits regardless of above format.
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; 
This expression can accept the format given below.
SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx:
     
     ^\\d{3}: Starts with three numeric digits.
    [- ]?: Followed by an optional "-"
    \\d{2}: Two numeric digits after the optional "-"
    [- ]?: May contain an optional second "-" character.
    \\d{4}: ends with four numeric digits.


Sunday, October 7, 2012

In java, How to print reversely in a given String?

In java, How to print reversely in a given String?

class ReveseString{
public static void main(String args[]){
String s="String is immutable";
for(int i=s.length()-1; i>=0; i--){
System.out.print(s.charAt(i));
}
}
}

How to write a program in java to display given certain pattern?

How to write a program in java to display given certain pattern?

1
12
123
1234
12345
 
class Example5{
public static void main(String args[]){
 for(int i=1;i<6;i++){
System.out.println();
 for(int j=1; j<=i; j++){
System.out.print(j);
 }
}
}
}


Thursday, November 24, 2011

How to read input from console in Java


How to read input from console -Java

There are two common ways to read input from console.

1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5

First we look up on InputStreamReader , BufferedReader example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystemInput {
  public static void main(String[] args) {

System.out.println("Enter something here to Read : ");

try{
   BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
   String s = bufferRead.readLine();

   System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}

  }
}

Another way is using Scanner class


import java.util.Scanner;

public class ReadConsoleScannerInput {
  public static void main(String[] args) {

 System.out.println("Enter something here to Read : ");

  String s;

       Scanner In = new Scanner(System.in);
       s = In.nextLine();

       In.close();          
       System.out.println(s);
  }
}

How to detect/match the words start with Uppercase letter in a given paragraph

Problem:
How to detect/match the word start with uppercase letter in a given paragraph. Write a program to accept three line of input as console input and display the words start with Uppercase letter only.
Example Input:
This Is very funny thing
My First coding is helloworld in java
Example is given for easy understand

Out Put:
This Is
My First
Example

Solution in java


import java.io.*;
import java.util.regex.*;
import java.util.Scanner;
public class problem9 {

public static void main(String[] args) {
String line1,line2,line3;
Scanner in = new Scanner(System.in);
String pattern = "(?U)\\b\\p{Lu}\\p{L}*\\b";  // match the words start with uppercase

line1 = in.nextLine();
line2 = in.nextLine();
line3 = in.nextLine();
String delimiter = "\\s";   //space delimiter
String[] words1 = line1.split(delimiter);
String[] words2 = line2.split(delimiter);
String[] words3 = line3.split(delimiter);

System.out.println();
for(int i=0; i<words1.length;i++){
if(words1[i].matches(pattern)){
System.out.println(words1[i]);
}
   }

for(int i=0; i<words2.length;i++){
if(words2[i].matches(pattern)){
System.out.println(words2[i]);
}  
   }

for(int i=0; i<words3.length;i++){
if(words3[i].matches(pattern)){
System.out.println(words3[i]);
}  
   }
}
}

Wednesday, November 23, 2011

Java program to print numbers from some range except the number end with some digit


Write a program to print numbers from 258 to 393 except the number end with 5.
output should be like this:
258
259
260
261
262
263
264
266
...
and so on

Solution to the above problem

class problem2{
public static void main(String args[]){


for(int i=258; i<394;i++){


 String aString = Integer.toString(i);
 char aChar = aString.charAt(2);
 String s1 = Character.toString(aChar);
 int n    = Integer.parseInt(s1);
if(n!= 5){
  System.out.println(aString); 
}
}
}
}



Tuesday, November 22, 2011

Working with java String.split() method

PROBLEM
Ross is an event organizer. He has received data regarding the participation of employees in two different events. Some employees have participated in only one event and others have participated in both events. Ross now needs to count the number of employees who have taken part in both events. The records received by Ross consist of employee ids, which are unique. Write a program that accepts the employee ids participating in each event (the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event:

1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005, so the program should give the output as:

2

Solution via Simple java code

import java.util.Scanner;
class problem3{
public static void compare(String id1[],String id2[]){
int k=0;
for(int i=0;i<id1.length; i++){
int x = Integer.parseInt(id1[i]);
for(int j=0; j<id2.length; j++){
int y = Integer.parseInt(id2[j]);
if(x==y){
k++;
}
}
}
System.out.println(k);
}
public static void main(String args[]){
   String firstLine;
String secondLine;
   Scanner in = new Scanner(System.in);
firstLine = in.nextLine();
secondLine = in.nextLine();
String delimiter = "\\,";
String[] array1 = firstLine.split(delimiter);    // array1{1001,1002,1003,1004,1005};
       String[] array2 = secondLine.split(delimiter);  // array2{1106,1008,1005,1003,1016,1017,1112};
compare(array1, array2);
}
}

Note: Input given via Console input(using scanner class).
After run this code via command prompt, you can type values and then enter. now you can see the output.

Calculating the distance travelled by a car at different time intervals


PROBLEM
Write a program to calculate the distance travelled by a car at different time intervals. The initial velocity of the car is 36 km/hr and the constant acceleration is 5 m/s2.

The formula to calculate distance is:

Distance Travelled = u*t+((a*t*t)/2) where,
u = initial velocity of the car (36 km/hr)
a = acceleration of the car (5 m/s2)
t = time duration in seconds

The program should accept 2 time intervals as the input (one time interval per line) and print the distance travelled in meters by the car (one output per line).

Definitions:
————
1 kilometer = 1000 meters
1 hour = 3600 seconds

Let us suppose following are the inputs supplied to the program

10
8

Then the output of the program will be

350
240

Solution in simple java code


import java.util.Scanner;
class problem4{
public static void calculateDistance(int t1,int t2){
int u = 10; // in m/s
int a = 5; // in m/s2
int distanceTravel1 = u*t1+((a*t1*t1)/2);
int distanceTravel2 = u*t2+((a*t2*t2)/2);
System.err.println(distanceTravel1);
System.err.println(distanceTravel2);
}
public static void main(String args[]){
int firstValue;
int secondValue;
   Scanner in = new Scanner(System.in);
    firstValue = in.nextInt();
secondValue = in.nextInt();
calculateDistance(firstValue,secondValue);
}
}

Note: Input given via Console input(using scanner class).
After run this code via command prompt, you should type two values (one value per line) and then enter. now you can see the output.

Friday, November 18, 2011

How to print a pyramid of numbers in Java


Write a program which will print the below structures according to the input provided to the program. The program should accept 3 inputs in the form of numbers between 1 and 9, both inclusive (one number per line) and then generate the corresponding structures based on the input.

Suppose the following sequence of numbers is supplied to the program:
3
2
4

Then the output should be:

  1
 2 2
3 3 3
 1
2 2
   1
  2 2
 3 3 3
4 4 4 4

Solution to above problem 

import java.util.Scanner;
class problem7{
public static void main(String args[]){
 int a,b,c;
 Scanner in = new Scanner(System.in);
 a = in.nextInt();
 b = in.nextInt();
 c = in.nextInt();
 int[] array={a,b,c};
    int k;
  for(int x=0; x<3; x++){
  int y = array[x];
  int z= y+1;
   for(int i=1;i<=y;i++){                    
   System.out.println();
   System.out.format("%"+z+"s", ""); 
    
    for(int j=1;j<=i;j++)
    {
    k=i;
    System.out.format("%"+1+"s", ""); 
    System.out.print(k);  
    }
    z--;
   }
  }
   }
}

Validating usernames in Java

Sam wants to select a username in order to register on a website.
The rules for selecting a username are:

1. The minimum length of the username must be 5 characters and the maximum may be 10.
2. It should contain at least one letter from A-Z
3. It should contain at least one digit from 0-9
4. It should contain at least one character from amongst @#*=
5. It should not contain any spaces

Write a program which accepts 4 usernames (one username per line) as input and checks whether each of them satisfy the above mentioned conditions.
If a username satisfies the conditions, the program should print PASS (in uppercase)
If a username fails the conditions, the program should print FAIL (in uppercase)

Suppose the following usernames are supplied to the program:
1234@a
ABC3a#@
1Ac@
ABC 3a#@

Then the output should be:
PASS
PASS
FAIL
FAIL

Solution to above problem:
import java.util.regex.*;
import java.util.Scanner;
public class problem5 {

public static void main(String[] args) {
String[] Array = new String[4];
Scanner in = new Scanner(System.in);
String pattern = "((?=.*[0-9])(?=.*[A-Z])(?=.*[@#*=])(?=[\\S]+$).{5,10})";

for(int i=0; i<Array.length;i++){
Array[i] = in.nextLine();
   }
System.out.println(""); //print empty line

for(int i=0; i<Array.length;i++){
if(Array[i].matches(pattern)){
System.out.println("PASS");
}
else {
System.out.println("FAIL");
}
       }
      in.close();

}
}


frog hops problem


Kermit, a frog hops in a particular way such that:

1. He hops 20cm in the first hop, 10cm in the second hop and 5cm in the third hop.
2. After three hops Kermit rests for a while and then again follows the same hopping pattern.

Calculate the total distance travelled by Kermit (in centimeters) for the provided number of hops. Exactly 4 numbers of hops will be provided to the program (one number per line) as per the below example.

Suppose the following number of hops is provided to the program:

4
6
3
5

Then the total distance covered should be displayed as follows:

55
70
35
65

Solution to Above Problem:


import java.util.Scanner;
public class problem1 {

public static void main(String[] args) {
int a,b,c,d;
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = in.nextInt();
int[] array = {a,b,c,d};
int k = 0;

for(int i=0; i<array.length; i++){
int n = array[i];
int x = n/3;
int y = n%3;
int z = x*35;

switch(y){
case 0: k = 0 + z; break;
case 1: k = 20 + z; break;
case 2: k = 30 + z; break;
case 3: k = 35 + z; break;
}
System.out.println(k);
}
}
}

Java Conversion (From X type to Y type)


integer to String :
int i = 20;
String str = Integer.toString(i);
   or
String str = "" + i

double to String :
String str = Double.toString(i);

long to String :
String str = Long.toString(l);

float to String :
String str = Float.toString(f);


String to integer :
   str = "50";
   int i = Integer.parseInt(str);
   or
   int i = Integer.valueOf(str).intValue();

String to double :
Double d = Double.valueOf(str).doubleValue();

String to long :
   long l = Long.valueOf(str).longValue();
   or
   Long l = Long.parseLong(str);

String to float :
Float f = Float.valueOf(str).floatValue();

char to String:
String s = String.valueOf('c');


decimal to binary :
int i = 42;
String bin = Integer.toBinaryString(i);

decimal to hexadecimal :
 int i = 42;
 String hexstr = Integer.toString(i, 16);
  or
 String hexstr = Integer.toHexString(i);
   or
(with leading zeroes and uppercase)
   public class Hex {
     public static void main(String args[]){
       int i = 42;
       System.out.print
         (Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
     }
   }

hexadecimal (String) to integer :
int i = Integer.valueOf("B8DA3", 16).intValue();
   or
int i = Integer.parseInt("B8DA3", 16);
 
integer to ASCII code (byte):
char c = 'A';
int i  = (int) c; // i =  65 DECIMAL

To extract Ascii codes from a String
String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
}

Note :To catch illegal number conversion, use the try/catch clause
Example to use try catch clause
try{
  i = Integer.parseInt(aString);
}
catch(NumberFormatException e) {
  .........
}