Java的方法
什么是方法?
方法就是一段可以重复调用的代码,增加了代码的复用性,提高开发效率,实现了一部分的程序减重。
拿平常话说就是,你做数学中的数列,没有公式,你得一步步算,现在我给了你一个方法,只要你一套,就能出结果,提高了你的解题速率,是不是这个道理?
声明一个方法的具体格式如下:
修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2,…){
执行语句
…
return 返回值;
}注意:返回值类型为void时,方法中的return语句可以省略不写,或者为return;
//如下方这块代码
public class MethodDemo {
public static void main(String[] args) {
System.out.println(method(5));
System.out.println(method(10));
System.out.println(method(100));
}
public static int method(int num) {
// 从1-num 进行求和。
return (num) * (1 + num) / 2;
}
}
方法的重载
关于方法重载,首先我们要明白一个问题,就是方法是用来干什么的?
如果一个方法sum()可以达到的目的是对两个数字进行求和,可是数的种类有很多,总不能针对每种求和情况都定义一个新的方法吧,显然这是不切实际的,光想名字就得掉多少头发。
故Java为我们引入了方法重载机制。就和人民币的面值一样,有不同的面额,但是都有一个共同的名字,钱,能够达到一个目的,满足我们的消费。
需要注意的是:方法的重载与返回值类型没有关系,但是需要满足的关系是:1,方法名相同;2,参数个数和参数类型不同,其中不同类型的参数的顺序不同也可以构成方法重载。
public class MethodDemo {
public static void main(String[] args) {
method(1, 2);
method(1.0, 2.0);
}
public static int method(int a,int b) {
return a+b;
}
public static double method(double a,double b) {
return a+b;
}
public static float method(float a,float b) {
return a+b;
}
public static float method(double a,float b) {
return (float) (a+b);
}
public static float method(float a,double b) {
return (float) (a+b);
}
}
Java中的数组
什么是数组?
数组就是一堆相同类型的数据的集合。
数组可以分为一维数组,二维数组。数组的定义方法
一维数组的定义方式:
1,int[] x= new int[5];
2,int[] x = {1,2,3,4};
二维数组的定义方式:
1,int[][] x = new int[5][5];
2,int[][] x = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
3,int[][] x = new int[5][];
x[0] = new int[5];
x[1] = new int[5];
x[2] = new int[5];
x[3] = new int[5];
x[4] = new int[5];
注意:数组的索引是从0-数组的长度-1的。常见的对数组的操作有数组遍历,数组最值,数组排序。
public class ArrayDemo {
public static void main(String[] args) {
//1,定义一个数组
int[] array = {10,5,7,20,6};
//2,遍历数组
for (int i = 0; i < array.length; i++) {
System.out.println("数组的第" + (i+1) + "位数位:" + array[i]);
}
//3,寻找数组的最值
int max = array[0]; //定义最值
for (int i = 1; i < array.length; i++) {
if (max<array[i]) {
max = array[i];
}
}
System.out.println("该数组的最大值为:" + max);
//4,对数组进行排序
System.out.println("对数组进行排序后:");
for (int i = 0; i < array.length; i++) {
int num;
for (int j = i+1; j < array.length; j++) {
if (array[i]>array[j]) {
num = array[i];
array[i] = array[j];
array[j] = num;
}
}
}
for (int i = 0; i < array.length; i++) {
System.out.println("数组的第" + (i+1) + "位数位:" + array[i]);
}
}
}
一个小练习
请利用数组和方法设计一个随机点名器。
import java.util.Random;
import java.util.Scanner;
public class RandomDemo {
public static void main(String[] args) {
// 1,定义一个数组
String[] array = { "张三", "李四", "王五", "赵六", "孙七" };
// 2,定义点名器的启动按钮
System.out.println("启动随机点名器,请输入1:");
Scanner scanner = new Scanner(System.in);
int start = scanner.nextInt();
if (start == 1) {
random(array);
}
}
public static void random(String[] array) {
int index = new Random().nextInt(array.length);
System.out.println("被点到名字的同学是:" + array[index]);
}
}