1.(将摄氏温度转换为华氏温度)编写程序,从控制台读入double型的摄氏温度,然后将其转换为华氏温度,并且显示结果:
代码如下:
public class Exercise1 {
public static void main(String [] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Celsius:");
double celsius = input.nextDouble();
double fahrenheit = (9.0 / 5) * celsius + 32;
System.out.print(celsius + " Celsius is " + fahrenheit + " Fahrenheit");
}
}
2.(计算圆柱体的体积)编写程序,读入圆柱体的半径和高,计算出圆柱的体积:
代码如下:
import java.util.*;
public class Exercise2 {
public static void main(String [] args) {
final double PI = 3.14159;
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter the radius and length of a cylinder:");
double radius = input.nextDouble();
double length = input.nextDouble();
double area = radius * radius * PI;//圆柱底面积
double volume = area * length;
System.out.println("The area is " + String.format("%.4f", area));//这里输出的是圆柱底面积
System.out.print("The volume is " + String.format("%.1f", volume));
}
}
3.(将英尺转换为米)编写程序,读入英尺数,将其转换为米数并显示结果。一英尺等于0.305米。
代码如下:
import java.util.*;
public class Exercise3 {
public static void main(String [] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter a value for feet: ");
double feet = input.nextDouble();
double meter = feet * 0.305;
System.out.print(feet + " feet is " + meter + " meters");
}
}
4.(将磅转换为千克)编写程序,将磅数转化为千克数。一磅等于0.454千克。
代码如下:
import java.util.Scanner;
public class Exercise4 {
public static void main(String [] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter a number in pounds: ");
double pound = input.nextDouble();
double kg = pound * 0.454;
System.out.print(pound + " pounds is " + kg + " kilograms");
}
}
5.(财务应用程序:计算小费)编写一个程序,读入一笔费用与酬金率,计算酬金和总钱数。例如:如果用户输入10作为费用,15%作为酬金率,计算结果显示酬金为$1.5,总费用为$11.5。
代码如下:
public class Exercise5 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter the subtotal and a gratuity rate:");
double subtotal = input.nextDouble();
double gratuityRate = input.nextDouble();
double gratuity = subtotal * gratuityRate * 0.01;
double total = subtotal + gratuity;
System.out.print("The gratuity is $" + gratuity + " and total is $" + total);
}
}
6.(求一个整数各位数的和)编写程序,读取一个在0和1000之间的整数,并将该整数的各位数字相加。
代码如下:
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Enter the number between 0 and 1000:");
int number = input.nextInt();
int onesPlace = number % 10;
int tensPlace = number % 100 / 10;
int hundredsPlace = number % 1000 / 100;
int thousandsPlace = number % 10000 / 1000;
int sumOfTheDigits = onesPlace + tensPlace + hundredsPlace + thousandsPlace;
System.out.print("The sum of the digits is " +sumOfTheDigits);
}