-
什么叫静态方法
特点和调用方式
-
工具类
定义:帮助我们做一些事情的,但是不描述任何事物的类
- 已经学习过的类
-
工具类的使用规则
-
练习
实操
类--ArrayUtil
package a02staticdemo2; public class ArrayUtil { //私有化构造方法 //目的:为了不让外界创建他的对象 private ArrayUtil(){} //需要定义为静态,方便使用 public static String printArr(int[] arr){ StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < arr.length; i++) { if (i<arr.length-1){ sb.append(arr[i]).append(","); }else if (i==arr.length-1){ sb.append(arr[i]).append("]"); } } return sb.toString(); } public static double getAverage(double[] arr){ double sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum / arr.length; } }
测试--TestDemo
package a02staticdemo2; public class TestDemo { public static void main(String[] args) { //测试工具类中的两个方法 int[] arr1 ={1,2,3,4,5}; String str = ArrayUtil.printArr(arr1); System.out.println(str);//[1,2,3,4,5] double[] arr2 = {1.1,2.2,3.3,4.4,5.5}; double average = ArrayUtil.getAverage(arr2); System.out.println(average);//3.3 } }
-
练习2
实操
工具类--studentsArrayUtil
package a03staticdemo3; import java.util.ArrayList; public class studentsArrayUtil { private studentsArrayUtil(){ } public static int age(ArrayList<students> ast){ int sum = 0; for (int i = 0; i < ast.size(); i++) { int age = ast.get(i).getAge(); if (age>sum){ sum = age; } } return sum; } }
学生类--students
package a03staticdemo3; public class students { private String name; private int age; private String gender; public students() { } public students(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
测试--studentsTest
package a03staticdemo3; import java.util.ArrayList; import java.util.Scanner; public class studentsTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<students> ast = new ArrayList<>(); for (int i = 0; i < 3; i++) { System.out.println("请输入学生姓名"); String name = sc.next(); System.out.println("请输入学生年龄"); int age = sc.nextInt(); System.out.println("请输入学生性别"); String gender = sc.next(); students st = new students(name,age,gender); ast.add(st); } int age = studentsArrayUtil.age(ast); System.out.println(age); } }
-