Coders PlayGround: Java

Learn to code and change the future!

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

Saturday, 19 August 2017

Conditional Statement in Java

August 19, 2017

Program to calculate the percentage of given 3 subjects and print the appropriate grade.

The if construct:

if(condition)
{
    // The desired operation
}




The if-else construct:

if(condition)
{
    // The desired operation
}else{
  // The desired operation
}



if - else if - else

if(condition1)
{
    // The desired operation
}else if(condition2)
{
    // The desired operation
}else
{
    // The desired operation
}


public class Grade
{
 public static void main(String args[])
 {
  int phy,chem,math;
  double a;
  phy=69;
  chem=81;
  math=80;
  a=(phy+chem+math)/3;
  System.out.println("Percentage: "+a);
  if(a>=75)
  {
   System.out.println("Grade:A");
  }
  else if(a>=50)
  {
   System.out.println("Grade:B");
  }
  else if(a>=35)
  {
   System.out.println("Grade:C");
  }
  else
  {
   System.out.println("Fail");
  }
 }
}
OUTPUT
Percentage: 76.0
Grade:A

Read More

Factorial of a number in Java

August 19, 2017
Hello everyone,

The factorial is denoted by "!"

So when we say, find 3 factorial, it is mathematically written as 3!

Now let us look into the formula as to how to find the factorial of any number.
Factorial of a number n is given by n! = n(n-1)(n-2)!

Suppose, factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

The two important facts you should know about factorial: 
  • The factorial of 1! = 1
  • The factorial of 0! = 1

Now let us write to program to find the find the factorial of a given number.

import java.util.Scanner;
public class Factorial
{
 public static void main(String args[])
 {
  int i, fact=1;
  System.out.println("Enter the Number:");
  Scanner in= new Scanner(System.in);
  int a=in.nextInt();
  for(i=1;i<=a;i++)
  {
   fact=fact*i;
  }
  System.out.println(factorial +"!="+fact);
 }
}
OUTPUT
Enter the Number:
5
Factorial != 120


Read More

Hello world in Java

August 19, 2017

Hello Friends,
This is a program to print a simple message:

Remember: The file name should be same as the class Name.

In this case, the file name will be First.java

class First
{
    public static void main(String args[ ])
    {
        System.out.println("hello World");
    }
}
OUTPUT
hello World
Read More
PropellerAds