数组

声明数组

package array;

public class Array1 {
	public static void main(String[] args) {
		//定义声明数组的方法
		int[] arr=new int[10];
		//
		int[] arr1= {1,2,3};
		//
		int[] arr2;
		arr2= new int[10];
		//
		arr2=new int[] {1};
		
		
		
	}
}

求某一个数的阶乘,使用了递归算法

package array;

import java.util.Scanner;

/*求某一个数的阶乘,使用了递归算法
 * 递归就是先找规则,然后写出规则就好了
 * 
 * */
public class Array3 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入值:");
		int n = scanner.nextInt();
		int a = factorials(n);
		System.out.println(n + "!=" + a);
	}
	public static int factorials(int m) {
		//当传入的值为1或者0时,输出自己,如果负数那么返回-1;递归调用自身
		if (m == 1 || m == 0) {
			return m;
		}
		if (m < 0) {
			return -1;
		}
		return m * factorials(m - 1);
	}
}

对于键盘上输入一组数求其平均值

package array;

import java.util.Scanner;

/*对于键盘上输入一组数求其平均值*/

public class Array4 {
	public static void main(String[] args) {
		// 键盘监听
		Scanner scanner = new Scanner(System.in);
		double[] array = new double[5];
		System.out.println("请输入5个数");
		// 对数组的每个值进行赋值,将键盘上输入的值按顺序赋值
		//这里做过测试,用foreach循环不可以赋值,考虑后会发觉这个循环只负责取出值来读,不负责 下标多少
		for (int i = 0; i < 5; i++) {
			// 读取键盘上的下一个值
			double sc = scanner.nextDouble();
			// 赋值
			array[i] = sc;
		}
		double sum = 0;
		// 对于数组进行遍历
		for (double a : array) {
			System.out.print(" " + a);
			sum += a;

		}
		System.out.println();
		System.out.println("这一组数的平均值是:" + sum);
	}

}

产生4位随机数,包括英文

package array;
//产生4位随机数,包括英文,
/*可以把Code方法写到一个类中
 * 把头两句写到构造器中,一调用就分割String
 * 后面的写到一个方法中,一调用就可以产生,其实和这个差不多,就是相当于封装了,
 * */
public class Array8 {
	public static void main(String[] args) {

		System.out.println(Code());
	}

	public static String Code() {
		// 下面两句代码就将string类型完全分割开并且放到了一个数组中
		String string = "qwertyuiopasdfghjklzxcvbnm0123456789";
		char[] c = string.toCharArray();

		// 取4个在数组中的随机位置的数,返回回去就好啦
		int i1 = (int) (Math.random() * c.length);
		int i2 = (int) (Math.random() * c.length);
		int i3 = (int) (Math.random() * c.length);
		int i4 = (int) (Math.random() * c.length);
		return "" + c[i1] + c[i2] + c[i3] + c[i4];
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值