1.打乱数组并随机输出:
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class practice {
public static void main(String[] args) {
int[] a = f();
//int[] a = new int[];
//f(a);
for (int i = 0;i < a.length;i++){
System.out.println(a[i]);
}
System.out.print("----------------------\n");
shuffle(a);
System.out.println(Arrays.toString(a));
}
public static int[] f(){
System.out.println("请输入此数组的长度:");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int[] a = new int[x];
for(int i = 0;i < a.length;i++){
a[i] = i+1;
}
return a;
}
public static void shuffle(int[] a){
for (int i = 0;i < a.length;i++){
Random random = new Random();
int j = random.nextInt(a.length);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
其中需要注意的是,有一个新的语句“Random”,通过new一个Random的对象,并使用其中的语法,且使用Random.netxInt(a.length)来输出a数组范围内的随机数。
最近学习了新的章节--类与对象,这一章是java中最重要的部分,这与下一章的继承与多态类都是非常重要的,我也做了非常多的练习
2.求圆锥体积
import java.util.Scanner;
class Circle{//定义底面圆类
private double radius;//定义底面半径
private double area;//定义底面积
double setRadius(double radius){//修改半径
if(radius<=0) {
System.out.println("输入的值有误");
return 0;
}
else
return this.radius = radius;
}
double getRadius(){//获得半径
return radius;
}
double getArea() {//获得面积
area = 3.14 * radius * radius;
return area;
}
}
class Circular{//定义圆锥类
Circle bottom;//通过定义bottom来储存Circle的地址
double height;//定义圆锥的高
void setBottom(Circle bottom){//设置底面是Circle的一个对象
this.bottom = bottom;
}
void setHeight(double height){//高
this.height = height;
}
double getVolume(){//求体积
/*if(bottom == null){
return (-1);
}
else*/
return (bottom.getArea()*height/3.0);
}
double getBottomRadius(){
return bottom.getRadius();
}
public void setBottomRadius(double radius){
bottom.setRadius(radius);
}
}
public class Volume {
public static void main(String[] args) {
//boolean t = true;
for(int t = 1;;t++) {
// getTime();
//int k = 1;
System.out.println("-----第"+t+"次循环-----");
double x, y;
Circle circle = new Circle();
x = ScannerR();
circle.setRadius(x);
y = ScannerH();
circle.getArea();
System.out.println("此圆锥的底面积为:" + circle.getArea());
Circular circular = new Circular();
circular.setHeight(y);
circular.setBottom(circle);
System.out.println("圆锥的体积:" + circular.getVolume());
}
}
static double ScannerR(){
System.out.println("请输入圆锥的半径:");
Scanner sc = new Scanner(System.in);
double i = sc.nextDouble();
return i;
}
static double ScannerH(){
System.out.println("请输入圆锥的高:");
Scanner sc = new Scanner(System.in);
double i = sc.nextDouble();
return i;
}
}
此程序分别定义了底面圆——circle类,圆锥——circular类,还有volume类,每段代码的具体功能通过注释写在代码旁,此程序的核心是通过再主类调用底面圆circle类来求出圆锥的底面积,再将刚刚定义的底面原类做为circular类中的一个变量进行值的传输,然后在主类中进行对象的创建,再调用对象内的各种计算方法,最后计算出结果并打印出来。
此外,此程序还使用了static、public、class、import等关键字,在下一期,我将进行一次总结,以我的视角和我现在学完后的知识来对类与对象进行一次知识讲解,目前我已经学到了异常章节,不得不说开始学习新语言的时候,尤其是在开始学习类与对象的时候有些地方非常的费解,但是随着网上资料的查找,和代码的练习,总得来说还是步入正轨,慢慢掌握了其中的一些精髓。
作为java小白,我水平还是不够的,这些文章也是质量低下哎,如有错误,感谢指正╮( ̄▽ ̄)╭