Solved Assignment Problems in Java – Part1
Q1. Create a program to compute the volume of a sphere. Use the formula: V = (4/3) *pi*r3 where pi is equal to 3.1416 approximately. The r is the radius of sphere. Display the result.
Sol:
import java.util.Scanner;
public class VolSphere{
public static void main(String [] args) {
Scanner Ob1 = new Scanner(System.in);
System.out.println(“Enter radius of sphere:”);
int r = Ob1.nextInt();
double pi = 3.1416;
double vol = (4/3)pirrr;
System.out.println(“Volume of sphere is: ” +vol);
}
}
Q2. Write a program the converts the input Celsius degree into its equivalent Fahrenheit degree. Use the formula: F = (9/5) *C+32.
Sol:
import java.util.Scanner;
public class CelsToFahrenheit{
public static void main(String[]args) {
Scanner Ob1 = new Scanner(System.in);
System.out.println(“Enter temperature in Celsius:”);
float C = Ob1.nextInt();
double Fh = (1.8*C)+ 32;
System.out.println(“Converted Fahrenheit value is: ” +Fh);
}
}
Q3. Write a program that converts the input dollar to its peso exchange rate equivalent. Assume that the present exchange rate is 51.50 pesos against the dollar. Then display the peso equivalent exchange rate.
Sol:
import java.util.Scanner;
public class DollarToPeso{
public static void main(String [] args) {
Scanner Ob1 = new Scanner(System.in);
System.out.println(“Enter amount of dollars to convert:”);
float dollar = Ob1.nextInt();
double peso = dollar*51.50;
System.out.println(“Equivalent peso is: ” +peso);
}
}
Q4. Write a program that converts an input inch(es) into its equivalent centimeters. Take note that one inch is equivalent to 2.54cms.
Sol:
import java.util.Scanner;
public class InchToCM{
public static void main(String [] args) {
Scanner Ob1 = new Scanner(System.in);
System.out.println(“Enter inches:”);
float inch = Ob1.nextInt();
double cm = 2.54* inch;
System.out.println(“Equivalent centimeter is: ” +cm);
}
}
Q5. Write a program that exchanges the value of two variables: x and y. The output must be: the value of variable y will become the value of variable x, and vice versa.
Sol:
import java.util.Scanner;
public class SwappingVariables{
public static void main(String [] args) {
Scanner Ob1 = new Scanner(System.in);
System.out.println(“Enter value of x: “);
int x = Ob1.nextInt();
System.out.println(“Enter value of y: “);
int y = Ob1.nextInt();
System.out.println(“Before swapping, values of x and y are” +x + “\t”+y);
int z = x;
x = y;
y =z;
System.out.println(“After swapping, values of x and y are: ” +x + “\t” +y);
}
}