如果您已经学习了Java的基础知识,那么现在正是解决一些实践问题的好时机。练习和解决问题将帮助您掌握 Java 编程语言并将您的技能提升到一个新的水平。
我整理了一些可以用于练习的 Java 编码问题。我还提供了 Java 代码解决方案和相应的输出供您参考。
1. Java程序检查给定数字是偶数还是奇数
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter a number: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
int x = number%2;
if(x==0){
System.out.println("The number is Even");
}
else{
System.out.println("The number is Odd");
}
}
}
输出:
2. 将摄氏温度转换为华氏温度的Java程序
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter temperature in Centigrade: ");
Scanner sc = new Scanner(System.in);
int c =Integer.parseInt(sc.nextLine());
float f = ((9*c)/5)+32;
System.out.println("Temperature in Fahrenheit is: "+f);
}
}
输出:
3. Java 程序求给定三个边的三角形面积
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the 1st side:");
int a= sc.nextInt();
System.out.println("Enter the 2nd side:");
int b= sc.nextInt();
System.out.println("Enter the 3rd side:");
int c= sc.nextInt();
if((a+b)>c && (a+c)>b && (b+c)>a)
{
double s=(a+b+c)/2.0;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("Area of Triangle is: " + area);
}
else
System.out.println("Area of the triangle does not exist");
}
}
输出:
4. Java程序求一组整数的平均值
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the count of numbers: ");
int count = Integer.parseInt(sc.nextLine());
int i = 0;
float sum = 0;
for(i=0;i<count;i++){
System.out.println("Enter an integer: ");
int x = Integer.parseInt(sc.nextLine());
sum = sum + x;
}
float avg = sum/count;
System.out.println("The average is: "+avg);
}
}
输出:
5. Java 程序求一组实数的乘积
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of real numbers: ");
int count = Integer.parseInt(sc.nextLine());
int i = 0;
float product = 1.0f;
for(i=0;i<count;i++){
System.out.println("Enter a real number: ");
float x = Float.parseFloat(sc.nextLine());
product = product * x;
}
System.out.println("The product of the numbers is: "+product);
}
}
输出:
以上就是动力节点小编介绍的"五个Java初学者练习题与解决方案",希望对大家有帮助,如有疑问,请在线咨询,有专业老师随时为您务。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习