Java入门级题目及源代码(上)

本文提供多个Java编程示例,包括变量声明与使用、计算平均值、计算圆锥体积及生成随机数并找出最大值等基本操作,适合初学者实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Problem 1]

Use Java to implement the following algorithm:

Step 1: declare a variable named x and assign 20 to it.

Step 2: declare a variable name y and assign 5 to it.

Step 3 compute the product of x and y and store it in z.

Step 4: display the value of all 3 variables.


public class E1_1 {
	public static void main(String args[]){
		int x=20;
		int y=5;
		int z=x+y;
		System.out.println("x="+x);
		System.out.println("y="+y);
		System.out.println("z="+z);
	}
}

[Problem 2]

1. Use Java to implement the following algorithm:

Step 1: declare a variable named value1 and assign 20.5 to it.

Step 2: declare a variable name value2 and assign 40.5 to it.

Step 3 compute the average of these 2 variables and store the result in another variable named ave.

 Step 4: display the value of all 3 varaibles.


public class E1_2 {
	public static void main(String args[]){
		double value1=20.5;
		double value2=40.5;
		double ave=(value1+value2)/2;
		System.out.println("value1="+value1);
		System.out.println("value2="+value2);
		System.out.println("ave="+ave);
	}
}

[Problem 3]

1. Write a Java program ConeVolume to compute and display the volume of a cone. All the necessary inputs should be obtained from the application runtime paramenters.

Volume of cone= 1/3*π*radiusOfBase2*height

Assume π=3.14


public class ConeVolume {
	public static void main(String args[]){
		double pi=3.14;
		double radiusOfBase=Double.parseDouble(args[0]);
		double height=Double.parseDouble(args[1]);
		double VolumeOfCone=(1.0/3)*pi*radiusOfBase*radiusOfBase*height;
		System.out.println("Volume of cone="+VolumeOfCone);
	}
}

[Problem 4]

1. Write a Java program which generates 5 random numbers ranging from 16 to 30 (inclusive) and reports the highest number. Your program output should resemble the following (note: the numbers are random):

Number 1  :  15

Number 2  :  15

Number 3  :  25

Number 4  :  30

Number 5  :  18

Highest Number is 30

Hint: Math.random() generate a double number in 0-1.

Math.floor(): floor the double number

   Or

     import java.util.*

  usage:

   Random  rand=new Random(50);

   rand.nextInt(14): generate 0-14 random integer.


public class E1_4 {
	public static void main(String args[]){
		int max=0;
		int n[]=new int[5];
		
		for (int i=0;i<5;i++){
			n[i]=(int)(Math.floor(16+14*Math.random()));
			System.out.println("Number "+(i+1)+"  :  "+n[i]);
			if (n[i]>max)max=n[i];
		}
		System.out.println("Highest Number is "+max);
	}
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值