0% found this document useful (0 votes)
512 views15 pages

Senthil JavaAssignmentProject Javacode

The Java program accepts a number n as a command line argument and prints all prime numbers between 1 and n. It defines a method to check if a number is prime and uses it in a loop from 2 to n to print prime numbers.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
512 views15 pages

Senthil JavaAssignmentProject Javacode

The Java program accepts a number n as a command line argument and prints all prime numbers between 1 and n. It defines a method to check if a number is prime and uses it in a loop from 2 to n to print prime numbers.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Question No 1:

Write a Java program that calculates and prints the simple interest using the
formula :
Simple Interest = PNR / 100
Input values P,N,R should be accepted as command line input as below.
e.g. java SimpleInterest 5 10 15
Solution:
/**
* @author senthiln
* This class <code>SimpleInterest</code> calculates the simple interest for giv
en
* principal, Number of years and Rate of Interest
*
*/
public class SimpleInterest
{
/**
* @param principal
* @param noOfYears
* @param rateOfInterest
* @return simpleInterest
*/
public double calculateSimpleInterest(double principal, int noOfYears, f
loat rateOfInterest)
{
double simpleInterest = 0;
simpleInterest = (principal*noOfYears*rateOfInterest)/100;
return simpleInterest;
}
/**
* Main Method to calculate Simple Interest
* @param args
*/
public static void main(String[] args)
{
double principal = 0;
int noOfYears = 0;
float rateOfInterest = 0;
try
{
principal = Double.parseDouble(args[0]);
noOfYears = Integer.parseInt(args[1]);
rateOfInterest = Float.parseFloat(args[2]);
/*
* Calculate Simple Interest
*/
SimpleInterest siObj = new SimpleInterest();
double simpleInterest = siObj.calculateSimpleInterest(pr
incipal,noOfYears,rateOfInterest);
/*
* Print Simple Interest
*/
System.out.println("Simple Interest : " + simpleInterest
);
}
catch(Exception e)
{
System.out.println("Error in parsing the input data : "
+ e.getMessage());
}

}
}
/*******************************************************************************
***********************/
Question No 2:
Write a program to compute sum of digits of a given number.
Solution:
import java.util.Scanner;

/**
* @author senthiln
* This class <code>SumOfDigits</code> calculates the sum of digits for a given
number
*
*/
public class SumOfDigits
{
/**
* Method to compute Sum of digits
* @param inputNumber
* @return sumOfDigits
*/
public int computeSum(int inputNumber)
{
int sumOfDigits = 0;
while (inputNumber > 0)
{
sumOfDigits += inputNumber % 10;
inputNumber /= 10;
}
return sumOfDigits;
}

/**
* Main Method to compute Sum of digits
* @param args
*/
public static void main(String[] args)
{
int sumOfDigits = 0;
System.out.println("Enter number to compute sum of digits : ");
/*
* Get User Input
*/
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
SumOfDigits sodObj = new SumOfDigits();
/*
* Compute Sum of Digits
*/
sumOfDigits = sodObj.computeSum(inputNumber);
System.out.println("\nSum of the digits is : "+ sumOfDigits);
}
}
/*******************************************************************************
***********************/
Question No 3:
The numbers in the following sequence are called the fibonacci numbers .
0 , 1 , 1 , 2, 3 , 5 , 8 , 13 , ..
Write a program using do ..while loop to calculate and print the first m
Fibonacci Numbers.
Solution:
import java.util.Scanner;
/**
* @author senthiln
* This class <code>FibonacciSeries</code> displays Fibonacci Series for a given
number
*
*/
public class FibonacciSeries
{
/**
* Method to print Fibonacci Series
* @param n
*/
public void printFib(int n)
{
int f0 = 0;
int f1 = 1;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++)
{
sb.append(",");
sb.append(f0);
int temp = f1;
f1 += f0;
f0 = temp;
}
/*
* Remove the first comma appended
*/
String fibSeries = sb.toString().substring(1, sb.toString().leng
th());
System.out.println("Fibonacci Series : " + fibSeries);
System.out.println(fibSeries);
}
/**
* Main Method to print Fibonacci Series
* @param args
*/
public static void main(String[] args)
{
System.out.println("Enter number to compute sum of digits : ");
/*
* Get User Input
*/
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
FibonacciSeries fibonacciSeries = new FibonacciSeries();
/*
* Display Fibonacci Series
*/
fibonacciSeries.printFib(inputNumber);
}
}
/*******************************************************************************
***********************/
Question No 4:
Write a program that converts a decimal number to Roman number. Decimal Number
is accepted as command line input at the time of execution.
Solution:
import java.util.Scanner;
/**
* @author senthiln
*
* This class <code>RomanNumeralConverter</code> converts decimal to RomanNumera
l.
*
* An object of type RomanNumeral is an integer between 1 and 3999. It can
* be constructed either from an integer or from a string that represents
* a Roman numeral in this range. The function <code>toString()</code> will ret
urn a
* standardized Roman numeral representation of the number. The function
* <code>toInt()</code> will return the number as a value of type <code>int</cod
e>.
*
*
*/
public class RomanNumeralConverter
{
private final int number; // The number represented by this Roman numeral.
/*
* The following arrays are used by the toString() function to construct
* the standard Roman numeral representation of the number. For each i,
* the number numbers[i] is represented by the corresponding string, letters[
i].
*/
private static int[] numbers = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1
};
private static String[] letters = { "M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I"
};
/**
* @param decimal
*
* Constructor. Creates the Roman number with the <code>int</code> value sp
ecified
* by the parameter. Throws a <code>NumberFormatException</code> if decimal
is
* not in the range 1 to 3999 inclusive.
*
*/
public RomanNumeralConverter(int decimal)
{
if (decimal < 1)
{
throw new NumberFormatException("Value of RomanNumeral must be positiv
e.");
}
if (decimal > 3999)
{
throw new NumberFormatException("Value of RomanNumeral must be 3999 or
less.");
}
number = decimal;
}

/* (non-Javadoc)
* @see java.lang.Object#toString()
*
* Return the standard representation of this Roman numeral.
*/
public String toString()
{
String roman = "";
int n = number;
// n represents the part of num that still has to be converted
to Roman numeral representation.
for (int i = 0; i < numbers.length; i++)
{
while (n >= numbers[i])
{
roman += letters[i];
n -= numbers[i];
}
}
return roman;
}

/**
* @return number
*
* Return the value of this Roman numeral as an int
*/
public int toInt()
{
return number;
}

/**
* @param args
*
* Main Method to Convert decimal to RomanNumeral
*/
public static void main(String[] args)
{
System.out.println("Enter an integer in the range 1 to 3999 and it
will be converted it to a Roman numeral.");
Scanner input = new Scanner(System.in);
int decimal = input.nextInt();
try
{
RomanNumeralConverter romanNumeral = new RomanNumeralCon
verter(decimal);
System.out.println(romanNumeral.toInt() + " = " + romanN
umeral.toString());
}
catch (NumberFormatException e)
{
System.out.println("Invalid input.");
System.out.println(e.getMessage());
}

} // end main()

} // end class RomanNumeralConverter


/*******************************************************************************
***********************/
Question No 5:
Write a program that prints prime numbers between 1 to n. Number n should be
accepted as command line input.
Solution:
import java.util.Scanner;
/**
* @author senthiln
* This class <code>PrimeNumber</code> displays all the PrimeNumber for a given
limit of numbers
*
*/
public class PrimeNumber
{
/**
* @param number
* @return
* Returns true if N is a prime number. A prime number is an integer gre
ater than 1
* that is not divisible by any positive integer, except itself and 1. I
f N has
* any divisor, D, in the range 1 < D < N, then it has a divisor in the
* range 2 to Math.sqrt(N), namely either D itself or N/D. So we only t
est possible
* divisors from 2 to Math.sqrt(N).
*/
public boolean isPrime(int number)
{
int divisor; // A number we will test to see whether it evenly d
ivides N.
if (number <= 1)
{
return false; // No number <= 1 is a prime.
}
int maxToTry = (int)Math.sqrt(number);
/* We will try to divide N by numbers between 2 and maxToTry; If
N is not evenly divisible
by any of these numbers, then N is prime. (Note that since Math
.sqrt(N) is defined to
return a value of type double, the value must be typecast to ty
pe int before it can
be assigned to maxToTry.)*/
for (divisor = 2; divisor <= maxToTry; divisor++)
{
if ( number % divisor == 0 ) // Test if divisor evenly d
ivides N.
{
return false; // If so, we know N is not prime.
}
// No need to continue testing.
}
/* If we get to this point, N must be prime. Otherwise, the func
tion would already have been terminated by
a return statement in the previous for loop.*/
return true; // Yes, number is prime.
} // end of function isPrime()
/**
* Main Method to invoke Prime Number
* @param args
*
*/
public static void main(String[] args)
{
System.out.println("Enter number to display Prime Numbers : ");
/*
* Get User Input
*/
Scanner input = new Scanner(System.in);
int num = input.nextInt();
StringBuffer sb = new StringBuffer();
PrimeNumber primeObj = new PrimeNumber();
for(int i = 1;i <= num;i++)
{
if (primeObj.isPrime(i))
{
sb.append(",").append(i);
}
}
/*
* Remove the first comma appended
*/
String primeNumbers = sb.toString().substring(1, sb.toString().l
ength());
System.out.println("The prime numbers from 1 to " + num + " are
: " + primeNumbers);
}//End of main
}// End of Class

/*******************************************************************************
***********************/
Question No 6:
Write a program to print the following output using the for loop.
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Solution:
import java.util.Scanner;
/**
* @author senthiln
* This class <code>SequenceNumbers</code> displays Sequence numbers for a given
number
*
*/
public class SequenceNumbers
{
/**
* @param number
* Method to display the numbers in sequence using for loop
*/
public void printSequence(int number)
{
for(int i=1; i<=number;i++)
{
StringBuffer output = new StringBuffer();
for(int j=1;j<=i;j++)
{
output.append(i+" ");
}
System.out.println(output.toString());
}
}
/**
* @param args
* Main method to invoke the methods
*/
public static void main(String[] args)
{
System.out.println("Enter number to print the sequence : ");
/*
* Get User Input
*/
Scanner input = new Scanner(System.in);
int inputNumber = input.nextInt();
SequenceNumbers seqObj = new SequenceNumbers();
/*
* Call Print Sequence Methods
*/
seqObj.printSequence(inputNumber);
}
}
/*******************************************************************************
***********************/
Question No 7:
Write a Java program that accepts the radius of a circle and displays the option
s as follows :
1. find diameter of a cicle.(2* radius)
2. find area of circle.( 22/7* radius * radius)
3. find circumference of a circle.( 2 *22/7 * radius)
4. Exit.
Use case statement to implement each option and display the corresponding output
.
Solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author senthiln
* This class <code>Circle</code> calculates Circle area, diameter
* and circumference based on input radius
*
*/
public class Circle
{
//Defining constant PI = 22/7
private final static double PI = 3.14;
/**
* @param option
* This method receives input and calculates Circle area, diameter
* and circumference based on input radius
*/
public void calculateCircleParams(float radius, int option)
{
switch(option)
{
case 1:
double diameter = 2 *radius;
System.out.println("Diameter of the circle "+dia
meter);
break;
case 2:
double area = PI*radius*radius;
System.out.println("Area of circle "+ area );
break;
case 3:
double circumference = 2 *(PI)*radius;
System.out.println("Circumfernce of Circle "+ ci
rcumference);
break;
case 4:
System.out.println("Exit.Thank you");
}
}
/**
* @param args
*
*Main method to invoke Circle
*/
public static void main (String args[])
{
System.out.println("Enter the radius of the circle");
BufferedReader br = new BufferedReader(new InputStreamReader(Sys
tem.in));
try
{
/*
* Get User Input on radius
*/
float radius = new Float (br.readLine()).floatValue();
System.out.println("1.Diameter of the circle\n2.Area of
circle\n3.Circumfernce of Circle\n4.Exit\nEnter the option");
/*
* Get User Input on radius
*/
int option = new Integer (br.readLine()).intValue();
/*
* Call the method to calculate Circle area, diameter
* and circumference based on input radius and user opti
on
*/
Circle circleObj = new Circle();
circleObj.calculateCircleParams(radius, option);
}
catch (NumberFormatException e)
{
System.out.println("Error in parsing input value - " + e
.getMessage());
}
catch (IOException e)
{
System.out.println("Error in reading input value - " + e
.getMessage());
}
}
}

/*******************************************************************************
***********************/
Question No 8:
Define a class called fruit with the following attributes:
1. Name of the fruit.
2. Single fruit or bunch fruit.
3. Price.
Define a suitable constructor and displayFruit() method that displays values of
all the attributes. Write a program that creates 2 objects of fruit class and
display their attributes.
Solution:

/**
* @author senthiln
* This class <code>Fruit</code> displays fruit Attributes
*
*/
public class Fruit
{
/**
* Fruit Attributes
*/
private String name;
private boolean bunch;
private int price;
/**
* @param name
* @param bunch
* @param price
*
* Constructor
*/
Fruit(String name, boolean bunch, int price)
{
this.name = name;
this.bunch = bunch;
this.price = price;
}
/**
* Method to display fruit Attributes
*/
public void displayFruit()
{
StringBuffer buff = new StringBuffer();
buff.append("\nFruit Name : "+ name);
if(bunch)
{
buff.append("\nBunch Fruit");
}
else
{
buff.append("\nSingle Fruit");
}
buff.append("\nPrice : "+price);
buff.append("\n------------------------------");
System.out.println(buff.toString());
}
/**
* @param args
* Main Method to invoke Fruit attributes
*/
public static void main(String[] args)
{
Fruit apple = new Fruit("Apple",false,100);
apple.displayFruit();
Fruit grape = new Fruit("Grape",true,50);
grape.displayFruit();
}
}
/*******************************************************************************
***********************/
Question No 9:
Write a program to find the Factorial of a number using Recursion. Factorial can
be defined as Factorial(n) = 1 * 2 * 3 .* (n-1) * n.
Solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
* @author senthiln
* This class <code>Factorial</code> to find Factorial for a given number
*
*/
public class Factorial
{
/**
* @param number
* @return factorialVal
* Calculate Factorial based on recursion
*/
public int calculateFact(int number)
{
int factorialVal;
if(number == 1)
{
return(1);
}
else
{
factorialVal = number*calculateFact(number-1); //Recursi
on to calculate Factorial
}
return factorialVal;
}
/**
* @param args
* Main Method to find Factorial for a given numbers
*/
public static void main(String[] args)
{
System.out.println("Please Enter the Number : ");
/*
* Get User Input
*/
BufferedReader buff = new BufferedReader(new InputStreamReader(S
ystem.in));
Factorial factObj = new Factorial();
int num = 1;
try
{
num = Integer.parseInt(buff.readLine());
}
catch (NumberFormatException e)
{
System.out.println("Error in parsing input value - " + e
.getMessage());
}
catch (IOException e)
{
System.out.println("Error in reading input value - " + e
.getMessage());
}
int factorial = factObj.calculateFact(num);
System.out.println("Factorial of "+ num +" is : "+ factorial);
}
}

/*******************************************************************************
***********************/

Question No 11:
Define an exception called NoMatchException that is thrown when a string is
not equal to Symbiosis . Write a Java program that uses this exception.
Solution:
/**
* @author senthiln
*
*
*/
public class ExceptionClass
{
//Defining a string Symbiosis
private static final String SYMBIOSIS = "Symbiosis";
/**
* @param str
* @throws NoMatchException
* Method to compare String and throw exception
*/
private static void compareString(String str) throws NoMatchException
{
if(str.equals(SYMBIOSIS))
{
System.out.println("Strings are equal");
}
else
{
throw new NoMatchException("Strings are Unequal"); //Thr
ows the exception to calling function
}
}
/**
* @param args
*/
public static void main(String[] args)
{
try
{
compareString(args[0]);
}
catch(NoMatchException e)
{
e.printStackTrace();
}
}
}
/**
* @author senthiln
* NoMatchExceptoion class
*
*/
class NoMatchException extends Exception
{
NoMatchException(String message)
{
super(message);
}
}

/*******************************************************************************
***********************/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy