Monday, January 30, 2023

Emi calculator in java code

Here's a simple Java code to calculate EMI (Equated Monthly Installment) using the formula:


import java.math.BigDecimal;

import java.math.RoundingMode;


public class EMI_Calculator {

  public static void main(String[] args) {

    double p = 10000;   // Loan amount

    double r = 0.05;    // Interest rate

    int n = 12;         // Loan tenure in months


    double emi = (p * r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);


    BigDecimal bd = new BigDecimal(emi).setScale(2, RoundingMode.HALF_UP);

    System.out.println("EMI: $" + bd.doubleValue());

  }

}


This code calculates the EMI for a loan of $10,000 with 5% interest rate for a tenure of 12 months. The output will be rounded to 2 decimal places using BigDecimal class. 

How to upload file in anguar?


You can use the Angular reactive forms module to create a form with a file input control. Here's a basic example of how to do it:


1. Import ReactiveFormsModule in your component's module:


import { ReactiveFormsModule } from '@angular/forms';


@NgModule({

  imports: [

    ReactiveFormsModule,

    ...

  ],

  ...

})

export class AppModule { }



2. In your component, create a form group and add a control for the file input:



import { FormGroup, FormBuilder } from '@angular/forms';


export class FileUploadComponent {

  form: FormGroup;


  constructor(private fb: FormBuilder) {

    this.form = this.fb.group({

      file: [null]

    });

  }

}



3. In your component's template, create a file input and bind it to the form control:


<form [formGroup]="form">

  <input type="file" formControlName="file">

</form>


4. Finally, in your component, you can access the selected file(s) using the value of the form control:


submit() {

  const file = this.form.get('file').value;

  console.log(file);

}

 <form [formGroup]="form"> - This is an Angular template directive that binds a FormGroup instance to the form element. The FormGroup is used to manage the values and validation of form controls.


<input type="file" formControlName="file"> - This is a file input element that is bound to a form control named "file".


<button (click)="submit()">Upload</button> - This is a submit button that triggers the submit() function when clicked.


import { FormGroup, FormBuilder } from '@angular/forms'; - This is an import statement for the FormGroup and FormBuilder classes from the @angular/forms module.


this.form = this.fb.group({ file: [null] }); - This is code that creates a new FormGroup instance using the FormBuilder and adds a single control named "file".


const file = this.form.get('file').value; - This code accesses the value of the "file" form control.


console.log(file) - This code logs the selected file to the console for debugging purposes.


Wednesday, September 19, 2018

Java Quick Program

1. Write a Code to generate Random numbers

public class GenerateRandomNumbers {

public static void main(String[] args) {
System.out.println(getRandomNumber());

}

public static double getRandomNumber() {
double x = Math.random();
return x;
}
}

2. Write code to verify a number is a perfect number or not.

This is a Java Program to Check if a given Number is Perfect Number. A perfect number is a positive integer that is equal to the sum of its proper positive divisors excluding the number itself.

public class NumberPerfect {

public static void main(String[] args) {

int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter any integer you want to check:");
n = s.nextInt();
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n) {
System.out.println("Given number is Perfect");
} else {
System.out.println("Given number is not Perfect");
}
}

int divisor(int x) {
return x;
}

}

3. Fibonacci series from 1 to 10. 

The Fibonacci sequence is a series of numbers where a number is the sum of previous two numbers. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

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

int count = 7, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series of " + count + " numbers:");

for (int i = 1; i <= count; ++i) {
System.out.print(num1 + " ");

/*
* On each iteration, we are assigning second number to the first
* number and assigning the sum of last two numbers to the second
* number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}

4. Write a program to find a Factorial of a number.

public static void main(String[] args) {
int n, c, fact = 1;

System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println("Number should be non-negative.");
else {
for (c = 1; c <= n; c++)
fact = fact * c;

System.out.println("Factorial of " + n + " is = " + fact);
}
}

5. Swap two numbers without using the third variable.

public class SwapWithoutThirdVariable {

public static void main(String[] args) {
System.out.println("Before swapping");
int x = 10;
int y = 20;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);
System.out.println("After swapping");
x = x + y;
y = x - y;
x = x - y;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);

}

}

6. Program to find greatest of three numbers.

public class GreatestNumber {

public static void main(String[] args) {
int x, y, z;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
x = s.nextInt();
System.out.print("Enter the second number:");
y = s.nextInt();
System.out.print("Enter the third number:");
z = s.nextInt();
if (x > y && x > z) {
System.out.println("Largest number is:" + x);
} else if (y > z) {
System.out.println("Largest number is:" + y);
} else {
System.out.println("Largest number is:" + z);
}
}

}

7. An Array of numbers given. .Find the largest two number and print it

public class LargestNumbers {

public static void main(String[] args) {
int n, l1, l2, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
if (n > 1) {
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Largest two numbers are:" + a[0] + " and " + a[1]);
} else {
System.out.println("Enter number greater than 1");
}

}

}


8. Reverse a number.

public class ReverseNumber {

public static void main(String[] args) {

int n, m, a = 0, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
m = n;
while (n > 0) {
x = n % 10;
a = a * 10 + x;
n = n / 10;
}
System.out.println("Reverse number: " + a);
}

}

9. Verify if a given number is a palindrome or not.(same concept of reversing a number)

public class Palindrome {

public static void main(String[] args) {

int n, m, a = 0, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter any number:");
n = s.nextInt();
m = n;
while (n > 0) {
x = n % 10;
a = a * 10 + x;
n = n / 10;
}
if (a == m) {
System.out.println("Given number " + m + " is Palindrome");
} else {
System.out.println("Given number " + m + " is Not Palindrome");
}
}

}

10. Armstrong number program.

public class ArmstrongNumber {

public static void main(String[] args) {
int num = 370, number, temp, total = 0;
number = num;
while (number != 0) {
temp = number % 10;
total = total + temp * temp * temp;
number /= 10;
}

if (total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}

}

Thursday, January 19, 2017

How to Calculate the Future Investment Value of Investment.

Below java program for calculate future investment value.
Here calculate s using the formula futureInvestmentValue =investmentAmount x (1 + monthlyInterestRate)^numberOfYears*12.

Output: 





Java code here.

package swain.swain;

import java.util.Scanner;

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

         Scanner input = new Scanner(System.in);

         System.out.println("Enter investment amount:");
         double investmentAmount = input.nextDouble();
         System.out.println("Enter annual interest rate in percentage:");
         double monthlyInterestRate = input.nextDouble();
         System.out.println("Enter number of years:");
         double numberOfYears = input.nextDouble();
         double futureInvestmentValue = investmentAmount * Math.pow((1 + (monthlyInterestRate / 1200)), (numberOfYears * 12));
         futureInvestmentValue = (int) (futureInvestmentValue * 100) / 100.0;
         System.out.println("Accumulated value is " + futureInvestmentValue + "\n");
    }
}


Oracle JRE will no longer trust MD5-signed code by default




Beginning with the April 2017 Critical Patch Update, JAR files signed using MD5 will no longer be considered as signed by the Oracle JRE.  Affected MD5-signed JAR files will no longer be considered trusted and as a result will not be able to run by default, such as in the case of Java applets, or Java Web Start applications.
This change in the JRE behavior is required because MD5 is no longer considered secure and is widely considered unsuitable for security use.  In fact, the MD5 with RSA algorithm stopped being the default JAR signing option with Java SE 6 released back in 2006.  It is critical that weak hashing algorithms (such as MD5) be deprecated when they are known to be weak so as to maintain the trust in the verification mechanism they provide.  
This change affecting MD5-signed JARS will be enabled by default no sooner than with Oracle Java SE 8u131 which will be released with the April 2017 Critical Patch Update, as well as in the corresponding releases of Oracle Java SE 7, Oracle Java SE 6 and Oracle JRockit R28, which will be available to qualified customers through My Oracle Support.
In order to prepare for this upcoming change, developers need to verify that their JAR files have not been signed using MD5.  You can do this with your own JARs by verifying your build process signs JARs using Java 6 or later without having deliberately chosen MD5.  If you are using JARS you did not sign or build yourself, you need to contact your vendor for more information.  If it can no longer be established if a JAR you are using has been signed with MD5, the recommended practice is to re-sign affected JAR files using a more modern algorithm.  Be sure to remove any existing MD5 signatures first before re-signing using the zip utility as follows:
zip -d test.jar 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*.DSA'
More technical information can be found in the October 2016 Critical Patch Update Release Notes for Java SE.
Oracle has already informed a number of software vendors, including source licensees, of the upcoming changes.  Users concerned about the effect of this change on third party applications should contact their respective vendor.
Cryptography is a dynamic field.  In order to keep users and developers informed about upcoming changes in this area, Oracle has recently published a new web page at java.com/cryptoroadmap.  This page provides information about upcoming cryptographic changes in Oracle JRE and Oracle JDK, and related technical instructions.


Apache FileUtils Examples.

Apache FileUtils Examples.



General file manipulation utilities.

Facilities are provided in the following areas:

1      Writing to a file.
2      Reading from a file.
3   Make a directory including parent directories.
4   Copying files and directories.
5     Deleting files and directories.
6   Converting to and from a URL.
7      Listing files and directories by filter and extension.
8   Comparing file content.
9    File last changed date.
1    Calculating a checksum.

Maven Repository
                <dependency>
                                                <groupId>commons-io</groupId>
                                                <artifactId>commons-io</artifactId>
                                                <version>2.4</version>
                                </dependency>

Examples.
package swain.swain;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.filefilter.SuffixFileFilter;

public class ApacheFileUtilsExample {

    private static final String PATH = "C:\\appdata\\";

    public static void main(String[] args) throws IOException {

         String fileString = FileUtils.readFileToString(new File(PATH + "file1.txt"));
         System.out.println("Reading file content:" + fileString);
         String fileString2 = FileUtils.readFileToString(new File(PATH + "file2.txt"));
         System.out.println("Reading content:" + fileString2);
         File file1 = new File(PATH + "file1.txt");
         File file2 = new File(PATH + "file2.txt");
         System.out.println("Comparing file content: " + FileUtils.contentEquals(file1, file2));

         FileUtils.copyDirectory(FileUtils.getFile(PATH), FileUtils.getFile(PATH + "copiedNewPath\\"));

         FileUtils.copyDirectory(FileUtils.getFile(PATH), FileUtils.getFile(PATH + "copiedFilterPath\\"), new SuffixFileFilter(".txt"));

         for (File f : FileUtils.getFile(PATH + "copiedFilterPath\\").listFiles()) {
             System.out.println("Contents of copiedFilterPath: " + f.getName());
         }

         File copy = FileUtils.getFile(PATH + "test1.txt");
         FileUtils.copyFile(file1, copy);
         System.out.println("Comparing file content:: " + FileUtils.contentEquals(file1, copy));

         for (File file : FileUtils.getFile(PATH).listFiles()) {
             System.out.println("File Name: " + file.getName());
         }

         FileUtils.deleteDirectory(FileUtils.getFile(PATH + "copiedFilterPath\\"));
         for (File file : FileUtils.getFile(PATH).listFiles()) {
             System.out.println("Contents of PATH after deletion: " + file.getName());
         }

         // Directories
         System.out.println("Temp Dir: " + FileUtils.getTempDirectory().getAbsolutePath());
         System.out.println("User Dir: " + FileUtils.getUserDirectory().getAbsolutePath());

         // Line Iterator
         LineIterator iter = FileUtils.lineIterator(file1);
         while (iter.hasNext()) {
             System.out.println("cmpFile1 lines: " + iter.next());
         }

         // Directory size
         System.out.println("Size of dir: " + FileUtils.sizeOfDirectory(FileUtils.getFile(PATH)) + " bytes.");

         // Ways of writing lines to a file.
         File fileToWrite1 = FileUtils.getFile(PATH + "file1.txt");
         File fileToWrite2 = FileUtils.getFile(PATH + "file2.txt");

         Collection<String> lines = new ArrayList<String>();
         lines.add("Hello world");
         lines.add("First Line");

         FileUtils.write(fileToWrite1, "Written with FileUtils!");
         FileUtils.writeLines(fileToWrite2, lines);

    }
}




Wednesday, January 18, 2017

Java Program: Print Pattern with star java example


To find out multiple example of star print pattern.


Output:



Java code.

package swain.swain;

public class PrintPattern {
public static void example1() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print first part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print new lint
System.out.println();
space = space + 2;
}

space = 8;
for (int i = 1; i <= 5; i++) {
// print first part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print new lint
System.out.println();
space = space - 2;
}
}

public static void example2() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print first part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = i; j >= 1; j--)
System.out.print("*");

// print new lint
System.out.println();
space = space + 2;

}
}

public static void example3() {
int space = 8;
for (int i = 1; i <= 5; i++) {
// print first part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print space
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print second part of the row
for (int j = 1; j <= i; j++)
System.out.print("*");

// print new lint
System.out.println();
space = space - 2;
}
}

public static void example4() {
int space = 0;
for (int i = 5; i >= 1; i--) {
// print spaces
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print stars
for (int j = 1; j <= i; j++)
System.out.print("* ");

// print new line
System.out.println();
space++;

}
}

public static void example5() {
int space = 4;
for (int i = 1; i <= 5; i++) {
// print spaces
for (int j = 1; j <= space; j++)
System.out.print(" ");

// print stars
for (int j = 1; j <= i; j++)
System.out.print("* ");

// print new line
System.out.println();
space--;

}
}

public static void main(String args[]) {
System.out.println("Example 1");
PrintPattern.example1();
System.out.println("Example 2");
PrintPattern.example2();
System.out.println("Example 3");
PrintPattern.example3();
System.out.println("Example 4");
PrintPattern.example4();
System.out.println("Example 5");
PrintPattern.example5();
}
}

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...