T.Y.B.B.A.(C.A.) Semester - V Practical Examination. Lab Course: (CA-506) Computer Lab Based on Core Java Solved slips

 







A) Write a ‘java’ program to display characters from ‘A’ to ‘Z’.

 SLIP 1 Q 1

SAVE CODE AS    "Slip1q1.java"


public class Slip1q1 {
public static void main(String[] args) {
for(char c='A';c<='Z';c++){
System.out.print(c+" ");
}
System.out.println();
for(char c='a';c<='z';c++){
System.out.print(c+" ");
}
}
}


Write a ‘java’ program to copy only non-numeric data from one file to another file

 Slip 1 Q 2

Save as         "Slip1q2.java"

 
import java.io.*;

public class Slip1q2 {
public static void main(String[] args) throws IOException {
System.out.println("reading file...");
FileReader fileReader = new FileReader("Slip1/src/sourcefile1q2.txt");
// enter your source file location
FileWriter fileWriter = new FileWriter("Slip1/src/destinationfile1Q2.txt");
// enter your destination file location
int data = fileReader.read();
System.out.println("writing file...");
while (data != -1){
String content = String.valueOf((char)data);
if(Character.isAlphabetic(data)) {
fileWriter.append(content);
}else if(content.equals(" ")){
fileWriter.append(" ");
}
data = fileReader.read();
}
System.out.println("\nCOPY FINISHED SUCCESSFULLY...");
fileWriter.close();
fileReader.close();
}
}





A) Write a java program to display all the vowels from a given string

 Slip 2 Q 1

SAVE CODE AS   "VowelsInString.java"


import java.util.Scanner;

public class Slip2q1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string to find vowels on it.");
String user_string = scanner.nextLine();
scanner.close();
int vowel_count = 0;
for(int i=0;i<user_string.length();i++){
if(user_string.charAt(i)=='a' ||user_string.charAt(i)=='e'
||user_string.charAt(i)=='i' ||user_string.charAt(i)=='o'
||user_string.charAt(i)=='u' ||user_string.charAt(i)=='A'
||user_string.charAt(i)=='E' ||user_string.charAt(i)=='I'
||user_string.charAt(i)=='O' ||user_string.charAt(i)=='U'){
vowel_count++;
System.out.println("Vowel found ("+user_string.charAt(i)+") at index "+i);
}
}
if (vowel_count == 0){
System.out.println("Vowel not found in given string.");
}
}
}




Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the position of the Mouse_Click in a TextField.

 Slip 2Q2

Save as     "Slip2q2"


CODE:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class Slip2q2 {
public static void main(String[] args) {
new MyFrame("Mouse Events");
}
}

class MyFrame extends JFrame {
TextField click_text_field, mouse_move_field;
Label click_text_label, mouse_move_label;
int x,y;
Panel panel;
MyFrame(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

panel =new Panel();
panel.setLayout(new GridLayout(2,2,5,5));
click_text_label = new Label("Co-ordinates of clicking");
mouse_move_label = new Label("Co-ordinates of movement");
click_text_field=new TextField(20);
mouse_move_field =new TextField(20);
panel.add(click_text_label);
panel.add(click_text_field);
panel.add(mouse_move_label);
panel.add(mouse_move_field);
add(panel);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
x=me.getX();
y=me.getY();
click_text_field.setText("X="+x+" Y="+y);
}
}
class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
mouse_move_field.setText("X="+ x +" Y="+y);
}
}
}






A) Write a ‘java’ program to check whether given number is Armstrong or not. (Use static keyword)

 

 Slip 3 Q 1

SAVE CODE AS         "Armstrong.java"


import java.util.Scanner;

public class Slip3Q1 {
static boolean is_armstrong(int n){
int temp,last,digits=0,sum=0;
temp = n;
while (temp>0){
temp=temp/10;
digits++;
}
temp = n;
while (temp>0){
last = temp%10;
sum+=Math.pow(last,digits);
temp=temp/10;
}
return n == sum;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check armstrong : ");
int number = scanner.nextInt();
scanner.close();
if (is_armstrong(number)){
System.out.println(number+" is a armstrong number.");
}
else {
System.out.println(number+" is not a armstrong number.");
}
}
}











Define an abstract class Shape with abstract methods area () and volume (). Derive abstract class Shape into two classes Cone and Cylinder. Write a java Program to calculate area and volume of Cone and Cylinder.(Use Super Keyword.)

 SLIP 3 Q 2

SAVE CODE AS         "AbstractShape.java"


import java.util.Scanner;

public class Slip3q2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Shape shape;
System.out.println("""
ENTER YOUR CHOICE
1. Cone
2. Cylinder""");
int choice = scanner.nextInt();
if (choice==1){
System.out.println("Enter radius");
int radius = scanner.nextInt();
System.out.println("Enter height");
int height = scanner.nextInt();
shape=new Cone(radius,height);
shape.area();
shape.volume();
}else if (choice==2){
System.out.println("Enter radius");
int radius = scanner.nextInt();
System.out.println("Enter height");
int height = scanner.nextInt();
shape=new Cylinder(radius,height);
shape.area();
shape.volume();
}else {
System.out.println("invalid input");
}
}
abstract static class Shape{
abstract void area();
abstract void volume();
}
static class Cone extends Shape {
int radius,height;
Cone(int radius,int height){
this.radius=radius;
this.height=height;
}
void area(){
float slant_height=(height*height)+(radius*radius);
float area = (float)(Math.PI*radius*(radius+Math.sqrt(slant_height)));
System.out.println("Area of Cone : "+area);
}
void volume(){
float volume = (float)(Math.PI*radius*radius*(height/3));
System.out.println("Volume of cone : "+volume);
}
}
static class Cylinder extends Shape {
int radius, height;
Cylinder(int r,int h){
radius =r;
height =h;
}
public void area(){
float area=(float)((2*Math.PI* radius * height)+(2*Math.PI* radius * radius));
System.out.println("Area of Cylinder : "+area);
}
public void volume(){
float volume=(float)(Math.PI* radius * radius * height);
System.out.println("Volume of Cylinder : "+volume);
}
}
}





A) Write a java program to display the alternate characters from a given string.

 SLIP 4 Q 1

SAVE CODE AS         "Alternatecharfromstr.java"


import java.util.Scanner;

public class Alternatecharfromstr {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print
    ("Enter a string :");
    String str = sc.nextLine();
    sc.close();
    for (int i=0;i<str.length();i+=2){ //run only 2 mulriple index
        System.out.print(str.charAt(i)+" ");
    }
    }
}





B) Write a java program using Applet to implement a simple arithmetic calculator. 


  1. import java.awt.*;
  2. import java.applet.*;
  3. import java.awt.event.*;
  4. public class Calculator extends Applet implements ActionListener
  5. {
  6.     TextField inp;
  7.     //Function to add features to the frame
  8.     public void init()
  9.     {
  10. 	setBackground(Color.white);
  11. 	setLayout(null);
  12. 	int i;
  13. 	inp = new TextField();
  14. 	inp.setBounds(150,100,270,50);
  15. 	this.add(inp);
  16. 	Button button[] = new Button[10];
  17. 	for(i=0;i<10;i++)
  18. 	{
  19. 	    button[i] = new Button(String.valueOf(9-i));
  20. 	    button[i].setBounds(150+((i%3)*50),150+((i/3)*50),50,50);
  21. 	    this.add(button[i]);
  22. 	    button[i].addActionListener(this);
  23. 	}
  24. 	Button dec=new Button(".");
  25. 	dec.setBounds(200,300,50,50);
  26. 	this.add(dec);
  27. 	dec.addActionListener(this);
  28.  
  29. 	Button clr=new Button("C");
  30. 	clr.setBounds(250,300,50,50);
  31. 	this.add(clr);
  32. 	clr.addActionListener(this);
  33.  
  34. 	Button operator[] = new Button[5];
  35. 	operator[0]=new Button("/");
  36. 	operator[1]=new Button("*");
  37. 	operator[2]=new Button("-");
  38. 	operator[3]=new Button("+");
  39. 	operator[4]=new Button("=");
  40. 	for(i=0;i<4;i++)
  41. 	{
  42. 	    operator[i].setBounds(300,150+(i*50),50,50);
  43. 	    this.add(operator[i]);
  44. 	    operator[i].addActionListener(this);
  45. 	}
  46. 	operator[4].setBounds(350,300,70,50);
  47. 	this.add(operator[4]);
  48. 	operator[4].addActionListener(this);
  49.     }
  50.     String num1="";
  51.     String op="";
  52.     String num2="";
  53.     //Function to calculate the expression
  54.     public void actionPerformed(ActionEvent e)
  55.     {
  56. 	String button = e.getActionCommand();
  57.         char ch = button.charAt(0);
  58. 	if(ch>='0' && ch<='9'|| ch=='.') 
  59. 	{ 
  60. 	    if (!op.equals("")) 
  61. 		num2 = num2 + button; 
  62. 	    else
  63. 		num1 = num1 + button;   
  64. 	    inp.setText(num1+op+num2); 
  65. 	} 
  66. 	else if(ch=='C') 
  67. 	{ 
  68. 	    num1 = op = num2 = ""; 
  69. 	    inp.setText(""); 
  70. 	}
  71. 	else if (ch =='=') 
  72. 	{ 
  73. 	    if(!num1.equals("") && !num2.equals(""))
  74. 	    {
  75. 		double temp;
  76. 		double n1=Double.parseDouble(num1);
  77. 		double n2=Double.parseDouble(num2);
  78. 		if(n2==0 && op.equals("/"))
  79. 		{
  80. 		    inp.setText(num1+op+num2+" = Zero Division Error");
  81. 		    num1 = op = num2 = "";
  82. 		}
  83. 		else
  84. 		{
  85. 		    if (op.equals("+")) 
  86. 		        temp = n1 + n2; 
  87. 		    else if (op.equals("-")) 
  88. 		        temp = n1 - n2; 
  89. 		    else if (op.equals("/")) 
  90. 	  	        temp = n1/n2; 
  91. 		    else
  92. 		        temp = n1*n2; 
  93. 		    inp.setText(num1+op+num2+" = "+temp); 
  94. 		    num1 = Double.toString(temp);
  95. 		    op = num2 = ""; 
  96. 	        }
  97.             }
  98. 	    else
  99. 	    {
  100. 		num1 = op = num2 = ""; 
  101. 		inp.setText("");
  102. 	    }
  103.         } 
  104. 	else 
  105. 	{ 
  106. 	    if (op.equals("") || num2.equals("")) 
  107. 		op = button; 
  108. 	    else 
  109. 	    { 
  110. 		double temp;
  111. 		double n1=Double.parseDouble(num1);
  112. 		double n2=Double.parseDouble(num2);
  113. 		if(n2==0 && op.equals("/"))
  114. 		{
  115. 		    inp.setText(num1+op+num2+" = Zero Division Error");
  116. 		    num1 = op = num2 = "";
  117. 		}
  118. 		else
  119. 		{
  120. 		    if (op.equals("+")) 
  121. 		        temp = n1 + n2; 
  122. 		    else if (op.equals("-")) 
  123. 		        temp = n1 - n2; 
  124. 		    else if (op.equals("/")) 
  125. 	  	        temp = n1/n2; 
  126. 		    else
  127. 		        temp = n1*n2; 
  128. 		    num1 = Double.toString(temp); 
  129. 		    op = button; 
  130. 		    num2 = ""; 
  131. 	        }
  132.             }
  133. 	    inp.setText(num1+op+num2);
  134.         }
  135.     }
  136. }
  137. /*
  138. <applet code = Calculator.class width=600 height=600>
  139. </applet>
  140. */



Slip 5 



A) Write a java program to display following pattern:

Slip 5 Q 1

Save code as         "pattern.java"


        5

        4 5

        3 4 5

        2 3 4 5 

        1 2 3 4 5 

public class pattern {
    public static void main(String[] args) {
        int n=5;
        for (int i=n;i>0;i--){
            for (int j=i;j<=n;j++){
                System.out.print(j+" ");
            }
            System.out.println();
        }
    }
}






import java.io.*;
class Slip12
{
public static void main(String args[]) throws Exception
{
for(int i=0;i {
File file=new File(args[i]);
if(file.isFile())
{
String name = file.getName();
if(name.endsWith(".txt"))
{
file.delete();
System.out.println("file is deleted " +file);
}
else
{
System.out.println(name + " "+file.length()+" bytes")
}
}
else
{
System.out.println(args[i]+ "is not a file");
}
}
}
}






SLIP 6


A) Write a java program to accept a number from user, if it zero then throw user defined Exception “Number Is Zero”, otherwise calculate the sum of first and last digit of that number. (Use static keyword).


import java.io.*;
class NumberZero extends Exception
{
      NumberZero()
      {}
}
class Number
{
      static int no;
      Number() throws IOException
      {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter no");
            no=Integer.parseInt(br.readLine());
            try
            {  
   if(no==0)
                  {
                  throw new NumberZero();
                  }
            cal();
            }//end of try
            catch(NumberZero e)
            {
                  System.out.println("no is zero");
            }
      }
      void cal() 
      {   
  int l=0,r=0;
            l = no%10;
            //System.out.println("no = "+no);
            if(no>9)
            {
                  while(no>0)
                  {
                  r = no%10
                  }
            System.out.println("Addotion of first and last digit = "+(l+r));
                              }
            else
            System.out.println("Addotion of first and last digit = "+l);
      }
}
class Slip19
{
      public static void main(String a[]) throws IOException
      {   
  Number n= new Number();
      }
}





B) Write a java program to display transpose of a given matrix.

 Slip 6 Q 2

Save code as             "Transposematrix.java"



import java.util.Scanner;

public class Transposematrix {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter rows of matrix : ");
        int row=sc.nextInt();
        System.out.print("Enter column of matrix : ");
        int col=sc.nextInt();
       
        int[][] matrix = new int[row][col];
        //create and insert value
        for (int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                System.out.print("element at index ["+i+"]["+j+"] :");
                matrix[i][j]=sc.nextInt();
            }
        }
        sc.close();
        //print value of matrix
        System.out.println("\nReal matrix :-\n");
        for (int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                System.out.print(matrix[i][j]+" ");
            }
            System.out.println();
        }
        System.out.println("\nTranspose of matrix :-\n");
        for (int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                System.out.print(matrix[j][i]+" ");
            }
            System.out.println();
        }

    }    
}




A) Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and Sphere.(use final keyword)

 Slip 8 Q 1

Save code as             "InterfaceCircleSphere.java"


import java.util.Scanner;

interface Shape{
    void area();
}
class Circle implements Shape{
    final float PI=3.14f;
    float areacircle,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of circle : ");
        radius=s.nextFloat();
    }
    public void area(){
    areacircle=PI*radius*radius;
    }
    public void show()
    {
    System.out.println("Area of circle is : "+areacircle);
    }
}

class Sphere implements Shape{
    final float PI=3.14f;
    float areasphere,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of sphere : ");
        radius=s.nextFloat();
    }
    public void area(){
        areasphere=4*PI*radius*radius;
    }
    public void show(){
        System.out.println("Area of Sphere is : "+areasphere);
    }
}
class InterfaceCircleSphere
{
    public static void main(String args[]){
        Circle s1=new Circle();
        s1.accept();
        s1.area();
        s1.show();
        Sphere s2=new Sphere();
        s2.accept();
        s2.area();
        s2.show();
    }
}







A) Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and Sphere.(use final keyword)

 Slip 8 Q 1

Save code as             "InterfaceCircleSphere.java"


import java.util.Scanner;

interface Shape{
    void area();
}
class Circle implements Shape{
    final float PI=3.14f;
    float areacircle,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of circle : ");
        radius=s.nextFloat();
    }
    public void area(){
    areacircle=PI*radius*radius;
    }
    public void show()
    {
    System.out.println("Area of circle is : "+areacircle);
    }
}

class Sphere implements Shape{
    final float PI=3.14f;
    float areasphere,radius;
    Scanner s=new Scanner(System.in);
    void accept(){
        System.out.print("Enter the Radius of sphere : ");
        radius=s.nextFloat();
    }
    public void area(){
        areasphere=4*PI*radius*radius;
    }
    public void show(){
        System.out.println("Area of Sphere is : "+areasphere);
    }
}
class InterfaceCircleSphere
{
    public static void main(String args[]){
        Circle s1=new Circle();
        s1.accept();
        s1.area();
        s1.show();
        Sphere s2=new Sphere();
        s2.accept();
        s2.area();
        s2.show();
    }
}







A) Write a java Program to display following pattern:

Slip 9 Q 1

Save code as         "Pattern1.java"


            1 

            0 1 

            0 1 0 

            1 0 1 0



public class Pattern1 {
    public static void main(String[] args) {
        int num = 4;
        for (int i=0;i<num;i++){
            for(int j=0;j<=i;j++){
                if (i<2){
                    if ((i+j)%2==0){
                        System.out.print("1 ");
                    }else{
                        System.out.print("0 ");
                    }
                }else{
                    if ((i+j)%2==0){
                        System.out.print("0 ");
                    }else{
                        System.out.print("1 ");
                    }
                }
            }System.out.println();
        }
    }
}




A) Write a java program to count the frequency of each character in a given string.

 Slip 10 Q 1

save code as             "Frequencyofchar.java"



import java.util.Scanner;

public class Frequencyofchar {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string :");
        String str = sc.nextLine() ;  
        int[] freq = new int[str.length()];  
        int i, j;  
        char string[] = str.toCharArray();  
         
        for(i = 0; i <str.length(); i++) {  
            freq[i] = 1;  
            for(j = i+1; j <str.length(); j++) {  
                if(string[i] == string[j]) {  
                    freq[i]++;  
                     
                    //Set string[j] to 0 to avoid printing visited character  
                    string[j] = '0';  
                }  
            }  
        }  
         
        System.out.println("Characters and their corresponding frequencies");  
        for(i = 0; i <freq.length; i++) {  
            if(string[i] != ' ' && string[i] != '0')  
                System.out.println(string[i] + "-" + freq[i]);  
        }  
    }
}




A) Write a menu driven java program using command line arguments for the following:

 SLIP 11 Q 1

Save code as         "calculator.java"


import java.util.Scanner;
public class calculator {
    public static void main(String[] args){
        int num1=0,num2=0,option,ex=0;
        Scanner sc = new Scanner(System.in);
        do{
            System.out.println("Enter your choice from the following menu:");
            System.out.println("1.Addition \n2.Subtraction \n3.Multiplication \n4.Division \n5.Exit");
            option = sc.nextInt();
            if(option>4 || option<0){
                if (option==5){
                    System.out.println("You want to Exit.");
                }else
                System.out.println("Invalid choice");
            }
            else{
                System.out.print("Enter the first number : ");
                num1=sc.nextInt();
                System.out.print("Enter the second number : ");
                num2=sc.nextInt();
            }
            switch(option){
                case 1:System.out.println("Addition of "+num1+" and "+num2+" is "+(num1+num2));
                break;
                case 2:System.out.println("Subtraction of "+num1+" and "+num2+" is "+(num1-num2));
                break;
                case 3:System.out.println("Multiplication of "+num1+" and "+num2+" is "+(num1*num2));
                break;
                case 4: if(num2==0)
                System.out.println("Error!!! In Division denominator cannot be 0!");
                else{
                    System.out.println("In division of "+num1+" by "+num2+" is "+(num1/num2)+" and remainder is "+(num1%num2));
                }
                break;
                case 5: break;
            }
            if(option==5){
                break;
            }else{
            System.out.println("Do you want to continue? \n1.Yes \n2.No");
            ex=sc.nextInt();
            }
        }while(ex==1);
        sc.close();
    }
}










A) Write a java program to accept ‘n’ integers from the user & store them in an ArrayList collection. Display the elements of ArrayList collection in reverse order.

 SLIP 13 Q 1

SAVE CODE AS             "arrayList.java"



import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class arrayList {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("enter limit of array : ");
        int num=sc.nextInt();
        ArrayList<String> alist=new ArrayList<>(num);

       
        for(int i=0;i<num;i++){
            System.out.println("Enter "+i+" Element of ArrayList :");
            String elmt=sc.next();
            alist.add(elmt);
        }
        sc.close();
        System.out.println("Orignal list :"+alist);
        Collections.reverse(alist);
        System.out.println("Reverse of a ArrayList is :"+alist);
    }
}







A) Write a java program to accept a number from a user, if it is zero then throw user-defined Exception “Number is Zero”. If it is non-numeric then generate an error “Number is Invalid” otherwise check whether it is palindrome or not

 Slip 30 Q 1

Save code as         "palindromexception"


import java.util.*;
class ZeroException extends Exception{
    ZeroException(){
        super("Number is 0");
    }
}
class palindromexception{
    public static void main(String[] args) {
        int r,sum=0,temp;
        try{
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
            sc.close();
            if(n==0){
                throw new ZeroException();
            }
            else{
                temp=n;
                while(n>0){
                    r=n%10;
                    sum=(sum*10)+r;
                    n=n/10;
                }
                if(temp==sum)
                System.out.println("palindrome number "+temp);
                else
                System.out.println("not palindrome number");
            }
               
        }catch (Exception e){
            System.out.println(e);
        }
    }
}








































Post a Comment

0 Comments