问题遇到的现象和发生背景
运行之后到输入性别的时候,性别输入不成功,而且一直出来性别输入不合法这句
问题相关代码,请勿粘贴截图
import java.util.Scanner;
public class The21 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Student1 s=new Student1();
System.out.println("请输入学生姓名");
String name=sc.next();
s.setName(name);
while(s.getAge()==0) {
System.out.println("请输入学生年龄:");
int age=sc.nextInt();
s.setAge(age);
}
while(s.getGender()==" "||s.getGender()==null) {
System.out.println("请输入学生性别:");
String gender=sc.nextLine();
s.setGender(gender);
}
System.out.println("当前学生姓名:"+s.getName()+"年龄:"+s.getAge()+"性别:"+s.getGender());
}
}
class Student1{
private String name;
private int age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0||age>200) {
System.out.println("年龄输入不合法:");
this.age=0;
}else {
this.age=age;
}
}
public String getGender(){
return gender;
}
public void setGender(String gender) {
if(gender!="男"&&gender!="女") {
System.out.println("性别输入不合法:");
this.gender=" ";
}else {
this.gender=gender;
}
}
}
运行结果及报错内容
请输入学生姓名
mike
请输入学生年龄:
20
请输入学生性别:
性别输入不合法:
请输入学生性别:
我的解答思路和尝试过的方法
我试过改while和setGender方法,但是没成功
我想要达到的结果
能正常运行就🆗,能成功输入姓名性别年龄