Object Oriented Programming-1 (Lab Sesion-4)



Basic JAVA Programming and using Methods and User Input Processing


      1.Write a method with following method header.


        public static int gcd(int num1, int num2)

 

  Write a program that prompts the user to enter two integers and compute the gcd of two integers.

Code :

// Java program to find GCD of two numbers

import java.util.Scanner; 
class Que_1
{
    
    static int gcd(int a, int b)
    {
    if (b == 0)
        return a;
    return gcd(b, a % b); 
    }
    
    public static void main(String[] args) 
    {
        int a,b;
      Scanner s = new Scanner(System.in);
      System.out.println("Enter first number : " );
      a = s.nextInt();
      System.out.println("Enter second number : " );
      b = s.nextInt();


        
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}


OUTPUT :



 


2.Write a test program that prompts the user to enter ten numbers. Create a method and invoke it to reverse the

 numbers, display the numbers. The input for the 10 numbers should be taken in one line. (the 10 numbers should be separated by space.)


Example: Enter 10 numbers: 0 6 33 50 99 47 9 45 80


                Output: The reversed numbers are: 80 45 9 47 99 50 33 6 0

Code :

import java.util.Scanner;

public class reverse_number {
    /** Main method */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); // Create a Scanner
        int[] numbers = new int[10];    // Create an array of length ten

        // Prompt the user to enter ten numbers
        System.out.print("Enter ten numbers: ");
        for (int i = 0; i < numbers.length; i++)
            numbers[i] = input.nextInt();

        // Invoke the method to reverse the numbers
        reverse(numbers);

        // Display the numbers
        for (int e: numbers) {
            System.out.print(e + " ");
        }
        System.out.println();
    }

    /** Method reverse reverses the array passed in the argument */
    public static void reverse(int[] list) {
        int temp;
        for (int i = 0, j = list.length - 1; i < list.length / 2; i++, j--) {
            temp = list[i];
            list[i] = list[j];
            list[j] = temp;
        }
    }
}



OUTPUT :



 



3.String Checker : Write a program to check if both halves of the String contain same number of characters. 


a. Take the input String from user.

b. Create a method as void stringChecker(String test){} and call the method using the input string.

c. Print “YES” if both the halves of the String contain same number of character and print “NO” otherwise. 

Ignore the case of the characters. If length of String is odd, ignore the middle character.

d. Example:

i. Input : abcxbcxa Output: YES

ii. Input: abCxbcxa Output: YES

iii. Input: abccaabc Output: NO

iv. Input: abcxxbcxa Output: YES


Code :

import java.util.*;
public class StringCheck {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        String str , ans;
        System.out.println("Enter Your String :- ");
        str = sc.nextLine();
        ans = StringChecker(str,str.length());
        System.out.println("Input : "+str+" ,Output : "+ans);
        sc.close();
    }
    
    static String StringChecker(String str,int len) {
        String ans = "Yes";
        int i=0;
        int[] right=new int[26],left=new int [26];
        str = str.toLowerCase();
        for(i=0;i<len/2;i++) 
            left[((int) str.charAt(i))-97]++;
        if(len%2 != 0) i=(len/2)+1;
        for(;i<len;i++) 
            right[((int) str.charAt(i))-97]++;
        for(i=0;i<len/2;i++) {
            if(left[((int) str.charAt(i))-97] != right[((int) str.charAt(i))-97]) ans = "No";
        }
        return ans;
    }}



OUTPUT :




4. Password Validator : We have a requirement for the password as given here.


a. Minimum 9 characters.

b. The alphabets must be between [a-z]

c. Should contain at least one Upper Case letter [A-Z]

d. Should contain at least 1 number [0-9].

e. Should contain at least one special character from [ _ or % or * or $].


                Your task is as below. 


 i. Create a method String passwordValidator(String password){}

 ii. Take the password as input from user.

 iii. Call the method with password as parameter.

 iv. The method will return “Password Accepted” if the password is valid. or “Invalid Password”  otherwise.

 v. Print the String returned by the method.


 Example:


 a. Input: demoPassword6$ Output: Password Accepted

 b. Input: demoPassword6& Output: Invalid Password

 c. Input: demopassword6$ Output: Invalid Password

 d. Input: deMopassword$ Output: Invalid Password


Code :

// package com.company;
import java.util.Scanner;                               

class Password{

    public static void main (String [] args) {

        String inputPassword;                           

        Scanner input = new Scanner (System.in);              

        System.out.print("Password: ");                     
        inputPassword = input.next();                       

        System.out.println(PasswordValidator(inputPassword));               
        System.out.println("");


        main(args);  // re-runs the program (Allows for multiple tests)

    }

    public static String PasswordValidator(String Password) {

        String result = "Valid Password";           // Sets the initial result as valid
        int length = 0;                     // Stores the number characters in the password
        int numCount = 0;                   // Variable used to store numbers in the password
        int capCount = 0;                   // Variable used to store capital letters in the password
        int scount = 0;

        for (int x =0; x < Password.length(); x++)
        {
            if ((Password.charAt(x) >= 47 && Password.charAt(x) <= 58) || (Password.charAt(x) >= 64 && Password.charAt(x) <= 91) ||
                    (Password.charAt(x) >= 97 && Password.charAt(x) <= 122) || ( Password.charAt(x)=='_' || Password.charAt(x)=='%' || Password.charAt(x)=='*' || Password.charAt(x)=='$')) {
                //Keep the Password
            } else {
                result = "Password Contains Invalid Character!";        //Checks that password contains only letters and numbers
            }

            if ((Password.charAt(x) > 47 && Password.charAt(x) < 58)) {         // Counts the number of numbers
                numCount ++;
            }

            if ((Password.charAt(x) > 64 && Password.charAt(x) < 91)) {         // Counts the number of capital letters
                capCount ++;
            }

            if( Password.charAt(x)=='_' || Password.charAt(x)=='%' || Password.charAt(x)=='*' || Password.charAt(x)=='$') {
                scount++;
            }


            length = (x + 1);  // Counts the passwords length



        } // Ends the for loop

        if (numCount < 1){                                  
            result = "Not Enough Numbers in Password!";
        }

        if (capCount < 1) {                                
            result = "Not Enough Capital Letters in Password!";
        }

        if (scount < 1) {                                 
            result = "Not Enough Sprcial charctor in Password!";
        }

        if (length < 9){                                    
            result = "Password is Too Short!";
        }

        return (result);                               

    }
}


OUTPUT :



 


5. Interest Calculator : you need to calculate the compound interest and value of the investment after each year by  taking the initial amount, interest rate and number of years as input from user.

a. Create a method double[] interestCalculator(doubleinitial_amount, doublenumber_of_years, double

nterest_rate){}

b. Take initial amount, interest rate and number of years as input from user.

c. Pass these  values  to  method.  The  method  will  return  a double array  that will have the  size equal  to number_of_years. The array will contain the amount by calculating the interest each year.

d. Print the content of array which is returned by the method.


Example:


Enter Initial Amount: 1000

Enter Number of Years: 5

Enter Interest Rate(%): 10

The output of the method will contain the double array with content array=[1100.00, 1210.00, 1331.00, 1464.10, 1610.51]


Print the values present in array in each line like:

The amount after 1 year = 1100.00

The amount after 2year = 1210.00

The amount after 3year = 1331.00

The amount after 4year = 1464.10

The amount after 5year = 1610.51


Code :

// package com.company;
import java.util.Scanner;

public class InterestCalculator
{
    public static double[] interestCalculator(double p, double n, double r)
    {
        double amount[] = new double[(int)n];
        for (int i=0; i<(int)n; i++)
        {
            amount[i] = p * Math.pow(1 + (r / 12), 12 * (i+1));
        }
        return amount;
    }

    public static void display(double display[])
    {
        for(int i=0; i<display.length; i++)
        {
            System.out.println("The amount after "+(i+1)+" year : " + display[i]);
        }
    }

    public static void main(String[] args)
    {
        Scanner Scan = new Scanner(System.in);
        System.out.println("Enter below details:");
        System.out.print("Initial Amount : ");
        double I_amount = Scan.nextDouble();
        System.out.print("Number of Year : ");
        double No_year = Scan.nextDouble();
        System.out.print("Intrest Rate(%) : ");
        double Intrest_rate = Scan.nextDouble();

        double result[] = interestCalculator(I_amount, No_year, Intrest_rate * 0.01);
        display(result);
    }
}

OUTPUT :






 

Download pdf here......

 


No comments:

Post a Comment