Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
907 views

Java Assignment

This document contains solutions to 10 programming questions in Java. Each question asks the reader to write a Java program or class to solve a specific problem. The solutions provide the full Java code to implement classes, methods, and main functions to calculate simple interest, digit sums, Fibonacci sequences, Roman numeral conversion, prime numbers, sequences, fruit properties, factorials, and vehicle subclasses with maximum speeds.

Uploaded by

naveen nagaraj
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
907 views

Java Assignment

This document contains solutions to 10 programming questions in Java. Each question asks the reader to write a Java program or class to solve a specific problem. The solutions provide the full Java code to implement classes, methods, and main functions to calculate simple interest, digit sums, Fibonacci sequences, Roman numeral conversion, prime numbers, sequences, fruit properties, factorials, and vehicle subclasses with maximum speeds.

Uploaded by

naveen nagaraj
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

http://groups.yahoo.

com/group/SCDL_2005/message/10633

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:

/**
* Class to calculate the Simple Interest
*/
class SimpleInterest
{
/**
* calculateInterest calculates the simple interest
*/
private static float calculateInterest(float p, float n, float r) {
return (p*n*r)/100;
}
/**
* Main method
*/
public static void main(String[] args)
{
//Convert the p,n & r to float
float p = Float.parseFloat(args[0]);
float n = Float.parseFloat(args[1]);
float r = Float.parseFloat(args[2]);

//call the calculateInterest


float si = calculateInterest(p,n,r);

//print the interest


System.out.println("Simple Interest : "+si);
}
}

--------------------------------------------------------------------------------\
------------------

Question No 2:
Write a program to compute sum of digits of a given number.

Solution:

import java.io.*;

/**
* Class to calculate the sum of digits
*/
class SumOfDigit
{
/**
* Main Method
*/
public static void main(String[] args) throws Exception {
System.out.println("Please Enter the value of N : ");
//Read the number
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
//convert the number to int
int num = Integer.parseInt(buff.readLine());
int sum=0;
//calculate the sum
for(;num > 0;sum+=num%10,num/=10);
//print the sum
System.out.println("\nSum of the digits is : "+sum);
}
}

--------------------------------------------------------------------------------\
-------------------

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.io.*;
/**
* Fibonacci Sequence
*/
public class FIBONACCI
{
public static void main(String args[])throws IOException {
System.out.println("Please Enter the value of M : ");
//Create the command line reader
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
//read the no. from command line & convert it to int
int num = Integer.parseInt(buff.readLine());
System.out.println("\nSeries is \n");
StringBuffer sb = new StringBuffer();
int[] f = new int[num]; //creates array length of 46
if(num >= 1) {
f[0] = 0; //first item in array (computer starts counting at 0 not 1)
sb.append(f[0]);
} if(num >= 2) {
f[1] = 1; //second item in array
sb.append(", " +f[1]);

} if(num >= 3) {
f[2] = 1; //third item in array
sb.append(", " +f[2]);
} if(num >= 4) {
int x = 3; //declares x of type int (integer)
do {
f[x] = f[x-1] + f[x-2];//calculates next element in array
sb.append(" ,"+f[x]);
x++;
} while(x<num);
}
System.out.println(sb.toString());
}
}

--------------------------------------------------------------------------------\
-----------------------

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.io.*;
/**
* Decimal to Roman conversion
*/
public class Roman {
//================================================================ constant
// This could be alternatively be done with parallel arrays.
// Another alternative would be Pair<Integer, String>
final static RomanValue[] ROMAN_VALUE_TABLE = {
new RomanValue(1000, "M"),
new RomanValue( 900, "CM"),
new RomanValue( 500, "D"),
new RomanValue( 400, "CD"),
new RomanValue( 100, "C"),
new RomanValue( 90, "XC"),
new RomanValue( 50, "L"),
new RomanValue( 40, "XL"),
new RomanValue( 10, "X"),
new RomanValue( 9, "IX"),
new RomanValue( 5, "V"),
new RomanValue( 4, "IV"),
new RomanValue( 1, "I")
};

//============================================================== int2roman
public static String int2roman(int n) {
if (n >= 4000 || n < 1) {
throw new NumberFormatException("Numbers must be in range 1-3999");
}
StringBuffer result = new StringBuffer(10);

//... Start with largest value, and work toward smallest.


for (RomanValue equiv : ROMAN_VALUE_TABLE) {
//... Remove as many of this value as possible (maybe none).
while (n >= equiv.intVal) {
n -= equiv.intVal; // Subtract value.
result.append(equiv.romVal); // Add roman equivalent.
}
}
return result.toString();
}

///////////////////////////////////////////////////////// inner value class


private static class RomanValue {
//============================================================== fields
//... No need to make this fields private because they are
// used only in this private value class.
int intVal; // Integer value.
String romVal; // Equivalent roman numeral.

//========================================================= constructor
RomanValue(int dec, String rom) {
this.intVal = dec;
this.romVal = rom;
}
}

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


System.out.println("Please Enter the Numeric value : ");
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(buff.readLine());
System.out.println("The Roman value of "+num +" is : "+int2roman(num));

}
}

--------------------------------------------------------------------------------\
----------------------------------

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.io.*;
/**
* Prime numbers
*/
class Prime
{
static boolean isPrime(int N) {
// Returns true if N is a prime number. A prime number
// is an integer greater than 1 that is not divisible
// by any positive integer, except itself and 1. If 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 test possible
// divisors from 2 to Math.sqrt(N).

int divisor; // A number we will test to see whether it


// evenly divides N.

if (N <= 1)
return false; // No number <= 1 is a prime.

int maxToTry = (int)Math.sqrt(N);


// 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 type int before it can
// be assigned to maxToTry.)
for (divisor = 2; divisor <= maxToTry; divisor++) {
if ( N % divisor == 0 ) // Test if divisor evenly divides 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 function would already have been terminated by
// a return statement in the previous for loop.

return true; // Yes, N is prime.

} // end of function isPrime()

public static void main(String[] args) throws Exception


{
System.out.println("Please Enter the value of N : ");
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(buff.readLine());
System.out.println("\n");
for(int i=1;i<=num;i++) {
if (isPrime(i))
{
System.out.println(i+" : is a prime no.");
}
}
}
}

--------------------------------------------------------------------------------\
---------------------------------------

Question No 6:

Write a program to print the following output using the for loop.
1
22
333
4444
55555

Solution:

/**
* Print Sequence
*/
class Sequence
{
public static void main(String[] args)
{
for(int i=1; i<=5;i++) {
StringBuffer output = new StringBuffer();
for(int j=1;j<=i;j++) {
output.append(i+" ");
}
System.out.println(output.toString());
}
}
}

--------------------------------------------------------------------------------\
----------------------------------------

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:

/**
* Fruit Properties
*/
class Fruit
{
private String name;
private boolean bunch;
private int price;

Fruit(String name, boolean bunch, int price) {


this.name = name;
this.bunch = bunch;
this.price = price;
}

public void displayFruit() {


StringBuffer buff = new StringBuffer();
buff.append("\nFruit Name : "+name);
if(bunch)
buff.append("\nFruit Bunch");
else
buff.append("\nSingle Fruit");
buff.append("\nPrice : "+price);
buff.append("\n------------------------------");
System.out.println(buff.toString());
}

public static void main(String[] args)


{
Fruit mango = new Fruit("Mango",false,50);
mango.displayFruit();
Fruit grape = new Fruit("Grape",true,100);
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.*;
/**
* Factorial Calculation
*/
class Factorial
{
private static int fact(int n) {
int k;
if(n==1)
return(1);
else
k=n*fact(n-1);
return k;
}

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


System.out.println("Please Enter the Number : ");
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(buff.readLine());
System.out.println("Factorial of "+num+" is : "+fact(num));
}
}

--------------------------------------------------------------------------------\
--------------------------------------------
Question No 10:

Write a class vehicle .Define suitable attributes and methods. Write subclasses
of
Vehicle like Car, Bicycle, Scooter. Assume suitable required attributes. Write
constructor for each and define a method maxSpeed() in each class which prints
the
maximum speed of the vehicle.

Solution:

/**
* Abstract class Vehicle
*/
abstract class Vehicle
{
String name;
int wheels;
int maxSpeed;

Vehicle(String name, int wheels, int maxSpeed) {


this.name = name;
this.wheels = wheels;
this.maxSpeed = maxSpeed;
}
/**
* Abstract method maxSpeed so that all the
* classes extending vehicle must implement maxSpeed
*/
abstract void maxSpeed();
}

/**
* Car extending Vehicle
*/
class Car extends Vehicle
{
Car() {
super("Car",4,150);
}
public void maxSpeed() {
System.out.println("\n"+name+" Max Speed : "+maxSpeed);
}
}
/**
* Bicycle extending Vehicle
*/
class Bicycle extends Vehicle
{
Bicycle() {
super("Bicycle",2,5);
}

public void maxSpeed() {


System.out.println("\n"+name+" Max Speed : "+maxSpeed);
}
}

/**
* Scooter extending Vehicle
*/
class Scooter extends Vehicle
{
Scooter() {
super("Scooter",2,100);
}

public void maxSpeed() {


System.out.println("\n"+name+" Max Speed : "+maxSpeed);
}
}

/**
* DisplayVehicle, instantiating the vehicles
*/
public class DisplayVehicle
{
public static void main(String ar[]) {
new Car().maxSpeed();
new Bicycle().maxSpeed();
new Scooter().maxSpeed();
}
}

--------------------------------------------------------------------------------\
----------------------------------

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:

/**
* Exception User
*/
class ExceptionUser
{
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");
}
}
public static void main(String[] args) {
try
{
compareString(args[0]);
}
catch(NoMatchException e)
{
e.printStackTrace();
}
}
}

class NoMatchException extends Exception


{
NoMatchException(String message) {
super(message);
}
}

--------------------------------------------------------------------------------\
----------------------------------

You might also like