创建类Student,拥有name,age,sex三个属性,有一个全参构造方法,为这三个属性添加getter和setter方法,并为Student添加toString方法。 读取用户在控制台输入的内容,通过BufferOutStrem将字符写到缓冲输出流中,
时间: 2023-09-10 09:12:53 浏览: 106
好的,我来回答你的问题。以下是代码实现:
```java
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;
public class Student {
private String name;
private int age;
private String sex;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入姓名:");
String name = scanner.next();
System.out.println("请输入年龄:");
int age = scanner.nextInt();
System.out.println("请输入性别:");
String sex = scanner.next();
Student student = new Student(name, age, sex);
OutputStream outputStream = new BufferedOutputStream(System.out);
outputStream.write(student.toString().getBytes());
outputStream.flush();
outputStream.close();
}
}
```
以上代码创建了一个`Student`类,其中包含了`name`、`age`和`sex`三个属性,以及对应的getter和setter方法。在主函数中,通过`Scanner`类读取用户在控制台输入的内容,创建一个`Student`对象,并将其转换为字符串后通过`BufferedOutputStream`输出到控制台。注意要对输出流进行`flush`操作,否则可能会出现输出不完整的情况。
阅读全文