Sunday 2 November 2014

java programming - java programs and solution - java-level-0 assignment 2

Java Assignment-2
gajjar premal

Class and Object and related Exercises
1.  Write a class to represent a rectangle with attributes length and breadth. Implement
methods for initializing a rectangle, and to calculate the area and perimeter of a rectangle.
Compile this program Rectangle.java.

Rectangle.java

public class Rectangle
{
public int hight,width,area,perimeter;
    Rectangle(int a,int b)
    {
        height=a;
        width=b;
    }   
   
    public int Area()
    {
        return (area=hight*width)   
    }

    public int Perimeter()
    {
        return (perimeter=2*(hight+width))   
    }
    public void Print()
    {
        System.out.println("Area="+area);   
        System.out.println("Perimeter="+perimeter);   
       
    }
}

testRectangle.java

import java.uti.Scanner

public class testRectangle
{
public static void main(String[] args)
{
int a,b;
Scanner number1= new Scanner(System.in);
Scanner number2= new Scanner(System.in);

a=number1.nextInt();
b=number2.nextInt();
Rectangle Rec=new Rectangle(a,b);
Rec.Area();
Rec.Perimeter();
Rec.Print();
}

}

2.  Make Rectangle.java an executable application by inserting a main() method as in Circle.java.
main() should instantiate the rectangle class a couple of time (i.e. creates a few new rectangle objects) and display the information about the rectangles on the VDU.



3.  Modify the class definition for Rectangle so that it has 2 constructors – the default one and one with 2 parameters.

Rectangle.java

public class Rectangle
{
public int hight,width,area,perimeter;

    Rectangle()
    {
        this.hight=5;
        this.width=5;   
    }
    Rectangle(int a,int b)
    {
        height=a;
        width=b;
    }   
   
    public int Area()
    {
        return (area=hight*width)   
    }

    public int Perimeter()
    {
        return (perimeter=2*(hight+width))   
    }
    public void Print()
    {
        System.out.println("Area="+area);   
        System.out.println("Perimeter="+perimeter);   
       
    }
}

testRectangle.java

import java.uti.Scanner

public class testRectangle
{
public static void main(String[] args)
{
int a,b;
Scanner number1= new Scanner(System.in);
Scanner number2= new Scanner(System.in);

a=number1.nextInt();
b=number2.nextInt();
Rectangle Rec1=new Rectangle(); //Default constructor
Rectangle Rec=new Rectangle(a,b); //Constructor with two arguments

Rec1.Area();
Rec1.Perimeter();
Rec1.Print();

Rec.Area();
Rec.Perimeter();
Rec.Print();
}

}



4.  Write a class for a Point using rectangular co-ordinates – Point.java. It will have two private
attributes, namely the x and y coordinates. Give it 2 constructors and 2 public methods for
returning its x and y co-ordinates namely methods x( ) and y( )

// The Point class definition
public class Point {
   // Private member variables
   private int x, y;   // (x, y) co-ordinates

   // Constructors
   public Point(int x, int y) {
      this.x = x;
      this.y = y;
   }
   public Point() {    // default (no-arg) constructor
      x = 0;
      y = 0;
   }

   // Public getter and setter for private variables
   public int getX() {
      return x;
   }
   public void setX(int x) {
      this.x = x;
   }
   public int getY() {
      return y;
   }
   public void setY(int y) {
      this.y = y;
   }

   // toString() to describe itself
   public String toString() {
      return "(" + x + "," + y + ")";
   }
}

5.  Write a class for line segment Segment.java which utilises the Point class (a line segment is
defined with its 2 end-points). Write appropriate constructors and methods for determining
the line segment’s length, the slope and angle (in degrees) it makes with the x-axis.
Hint use the class methods
static double Math.atan( double x) returns angle in radians
static double Math.toDegrees( double a) converts radians to degrees Add a
public static void main( String arg[ ] )   method to this class to make it an application and
get it to create a line segment and apply its   methods.
6.  Given the following class, called NumberHolder, write some code that creates an instance of
the class, initializes its two member variables, and then displays the value of each member variable.
public class NumberHolder {
public int anInt;
public float aFloat;
}

public class NumberHolderDisplay {
    public static void main(String[] args) {
    NumberHolder aNumberHolder = new NumberHolder();
    aNumberHolder.anInt = 1;
    aNumberHolder.aFloat = 2.3f;
    System.out.println(aNumberHolder.anInt);
    System.out.println(aNumberHolder.aFloat);
    }
}
7. Write a program which prints current DateTime in this format “ YYYY-MM-DD HHMMSS”

public static void main(String args[]) {

  String s;
  Format formatter;
  Date date = new Date();
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
  s = formatter.format(date);
  System.out.println(s);
}
}

8. Write Book and Author class as shown in Class diagram below
-  Write a program called TimeTable to produce the multiplication table of 1 to 9 as shown
below
  1  2 .... 9
1  1  2  .  9
2  2  4  .  18
3  3  6  .  27
.   .   .   .   .
.   .   .   .   .
9   9  18 .  81


9.  Write a program called TestPalindromicWord, that prompts user for a word and prints
xxx isis not a palindrome (A word that reads the same backward as forward is called
a palindrome, e.g., mom, dad, racecar, madam)
10.  Write a program that declares and initializes an array a[] of size 1000 and accesses a[1000]. Does your program compile What happens when you run it

int [ ] a = new int [1000];
for(int i=0;i<1000;i++)
a[i]=i;
int x=a[1000];it is wrong because the program cannot access 1000 so it can access a[999] , the program can
access from 0 to 999 when you initialized  the size of array 1000.

11.  Describe and explain what happens when you try to compile a following
statement
int N = 1000;
int[] a = new int[NNNN];

public class HugeArray {

    public static void main(String[] args) {
        int N = 1000;
        int[] a = new int[N*N*N*N];
    }
}

12.  Write a code fragment that reverses the order of a one-dimensional
array a[] of double values.

    int N = a.length;
    for (int i = 0; i < N/2; i++) {
        double temp = a[N-i-1];
        a[N-i-1] = a[i];
        a[i] = temp;
    }


13.  What is wrong with the following code fragment
int[] a;
for (int i = 0; i  10; i++)
a[i] = i  i;

Solution: It does not allocate memory for a[] with new. The code results in a variable might not have
been initialized compile-time error

14.  What values does the following code put in the array a
N = 10;
int[] a = new int[N];
a[0] = 0;
a[1] = 1;
for (int i = 0; i  N; i++)
a[i] = a[i-1] + a[i-2];
System.out.println(a[i]);

Solution : Error, it is out of range of the index (Array Index Out Of Bounds Exception).

15.  Pass number of elements numbers from command line and print large number from that array

import java.util.*;

public class Testbignum
{
    public static void main(String[] args)
    {
        Bigarray=new int[5];
        for(int i=0;i<5;i++)
        {
            Bigarray[i]=args[i];       
        }
        int max=Bigarray[0];
        for(int i=0;i<5;i++)
        {
            if(Bigarray[i]>max)
            {
                max=Bigarray[i];   
            }               
       
        System.out.println("Big Number From array=" + max);       
        }
           
    }
}


16.  Pass number from command line and identify number is Odd, Even and also identify number is prime or not

import java.util.*;

public class Oddevenprime
{
public static void main(String args[])
{
    int Oddeven=args[0];
    int count=0;
    if((Oddeven % 2)==0)
    {
        System.out.println("Given number is Even");   
    }
    else
    {
        System.out.println("Given number is Odd");   
    }
   
    if(Oddeven==1)
    {
        System.out.println("Given number is Prime Number");       
    }
    else
    {
        for(int i=2 ; i< Oddeven;i++)
        {
            if((Oddeven % i)==0)
            {count++;}
               
        }   
        if(count==0)
        {System.out.println("Given number is not Prime Number");        }
        else
        {System.out.println("Given number is Prime Number");        }   
    }
}

}

17.  What does the following code print
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
System.out.println(a == b);

Solution: It prints false. The == operator compares whether the (memory addresses of the) two arrays are identical, not whether their corresponding values are equal.

18.  Replace specified string with given string.

import java.io.*;
public class Test{
public static void main(String args[]){
String Str=new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :");
System.out.println(Str.replace('o','T'));
System.out.print("Return Value :");
System.out.println(Str.replace('l','D'));
}
}

19.  Generating 10 random integers in user defined range (take range value from commandline parameter)

import java.util.*;

public class TestRandom
{
public static void main(String args[])
{
Random rand=new Random();
String a=args[0];
int b=Integer.parseInt(a);
for(int i=0 ;i<10;i++)
{
System.out.println(rand.nextInt(b);
}
}

}

20.  Generating random integers in the range 1..10

import java.util.*;

public class TestRandom
{
public static void main(String args[])
{
Random rand=new Random();

for(int i=0 ;i<10;i++)
{
System.out.println(rand.nextInt(10);
}
}

}

21.   Use Math functions
1. Find absolute value of float, int, double and long using Math.abs
2. Find exponential value of a number Math.exp
3. Find maximum of two numbers using Math.max
4. Find power using Math.pow
5. Find square root of a number using Math.sqrt
6. Round Java float and double numbers using Math.round

import java.util.*;
public class Mathop{
public static void main(String args[]){
Integer a =-8;
double d =-100;
float f =-90;
System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));

double x =11.635;
double y =2.76;
System.out.printf("The value of e is %.4f%n",Math.E);
System.out.printf("exp(%.3f) is %.3f%n", x,Math.exp(x));

System.out.println(Math.max(12.123,12.456));
System.out.println(Math.max(23.12,23.0));

System.out.printf("pow(%.3f, %.3f) is %.3f%n",x, y,Math.pow(x, y));

System.out.printf("sqrt(%.3f) is %.3f%n", x,Math.sqrt(x));

System.out.println(Math.round(d));
System.out.println(Math.round(f));
}
}


22. Use String functions
1.  Check if a string is present at the current position in another string.
2.  Checks if String contains a search String irrespective of case, handling null
3.  Checks if String contains a search character, handling null
4.  Case insensitive check if a String starts with a specified prefix. (i.e Pass 2 string
parameters from command line, where 1st parameter consider as prefix and
another one is your statement. Now check your statement starts with given prefix)
5.  Case insensitive check if a String ends with a specified prefix. (i.e Pass 2 string
parameters from command line, where 1st parameter consider as prefix and
another one is your statement. Now check your statement ends with given prefix)
6.  Get the difference between two strings (i.e pass 2 string parameters from command
line and create one method and name it stringDiff which takes 2 string parameter
and identifies difference between 2 strings)
7.  Counts how many times the substring appears in the larger String.
Java Assignment-2
8.  Split given string using given delimiter
23.  Exercise using condition and loop
1.  Write program which takes “Subject Marks” as command parameter and prints message like 1st class, 2nd Class, Pass or Fail (Consider below 50 fail, 50 to 60 pass, 60 to 70 2nd class and 70 to 80 1st class)
2.  Write a program which takes 2 command line value (1 “Statement” and 2 “t” occurrence of character) – In output print number of occurrence of given character in given statement
3.  Write “Reverse” string program
4.  Write a program which prints below patterns
a)
#
# #
# # #
# # # #
# # # # #
# # # # # #
# # # # # # #
# # # # # # # #

public class Pattern
{
public static void main(String args[])
{
for(int i=1;i<6;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}


b)
# # # # # # # #
# # # # # # #
# # # # # #
# # # # #
# # # #
# # #
# #
#

public class Pattern
{
public static void main(String args[])
{
for(int i=1;i<6;i++)
{
for(int j=6;j>=i;j--)
{
System.out.print("*");
}
System.out.print("\n");
}
}
}

c) Diamond
#
# # #
# # # # #
# # # # # # #
# # # # # # # # #
# # # # # # # # # # #
# # # # # # # # #
# # # # # # #
# # # # #
# # #
#

public class Pattern
{
public static void main(String args[])
{
for(int i=1;i<6;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print("*");
System.out.print("\n");
}
for(int i=2;i>=1;i--)
{
for(int j=1;j<=i;j++)
}
System.out.print("*");
System.out.print("\n");
}
}
}

5.  Use while loop to calculate sum of given range (pass number range from command-prompt, like 10 50, then perform sumation using all numbers between 10 to 50)

import java.util.*;
public class Sum{
public static void main(String args[])
{
int sum=0;
int start=Integer.parseInt(args[0]);
int stop=Integer.parseInt(args[1]);
while(start<=stop)
{
sum=sum+start;
start++;
}
System.out.println("Sum of all number="+sum);
}

No comments: