定义一个有关学生的Student类,内含类成员变量: String name、String sex、int age,所有的变量必须为私有(private)。 1.编写有参构造函数: 能对name,sex,age赋值。 2.覆盖toString函数: 按照格式:类名 [name=, sex=, age=]输出。使用idea自动生成,然后在修改成该输出格式 3.对每个属性生成setter/getter方法 4.main方法中 •输入1行name age sex , 调用上面的有参构造函数新建对象。 输入样例: tom 15 male 输出样例: Student [name='tom', sex='male', age=15]
时间: 2023-12-10 09:37:42 浏览: 58
下面是Student类的实现代码:
```java
public class Student {
private String name;
private String sex;
private int age;
public Student(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
@Override
public String toString() {
return "Student [name='" + name + "', sex='" + sex + "', age=" + age + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
int age = scanner.nextInt();
String sex = scanner.next();
Student student = new Student(name, sex, age);
System.out.println(student);
}
}
```
对于输入样例 `tom 15 male`,程序会输出 `Student [name='tom', sex='male', age=15]`。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)