案例:
以字符串的形式从键盘录入学生信息,例如:“张三,20”
从该字符串中切割出有效数据,封装为Student学生对象
实现步骤:
1.编写Student类,用于封装数据
2.键盘录入一个字符串吗,用Scanner实现
3.根据逗号切割字符串,得到 张三 20
String[] split(String regex):根据传入的字符串作为规则进行切割将切割后的内容存入字符串数组中,并将字符串数组返回
4.从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
5.调用对象getXxx方法,取出数据并打印。
import com.pojo.Student;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
//1.键盘录入一个字符串,用Scanner实现
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生信息:");
String stuInfo = sc.nextLine();
//2.根据逗号切割字符串,得到 张三 20
String[] arr = stuInfo.split(",");
//3.从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
Student stu = new Student(arr[0],arr[1]);
//4.调用对象getXxx方法,取出数据并打印
System.out.println(stu.getName() + "..." + stu.getAge());
}
}