我正在尝试使用Java对象的基本原理,但是尝试时遇到了这个问题
我有狗班
public class Dogs {
private String Name;
private int Age;
private String Color;
private String Owner;
public Dogs() {
this.Name = "Rex";
this.Age = 5;
this.Color = "black";
this.Owner = "John";
}
public Dogs(String name, int age, String color, String owner) {
this.Name = name;
this.Age = age;
this.Color = color;
this.Owner = owner;
}
//all the getters and setters
和主班
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Dogs my_dog = new Dogs();
System.out.println("What is the dog's name? ");
my_dog.setName(input.next());
System.out.println("What is the dog's age? ");
my_dog.setAge(input.nextInt());
System.out.println("What is the dog's color? ");
my_dog.setColor(input.nextLine());
System.out.println("What is the owner's name? ");
my_dog.setOwner(input.nextLine());
}
}
当我运行它时,它可以很好地打印两个问题,但比下一个跳过...
这是转存:
What is the dog's name?
pil
What is the dog's age?
7
What is the dog's color?
What is the owner's name?
我该如何解决?
请在读取年龄即整数值之后添加input.nextLine()。
有关详细信息refer this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Dogs my_dog = new Dogs();
System.out.println("What is the dog's name? ");
my_dog.setName(input.next());
System.out.println("What is the dog's age? ");
my_dog.setAge(input.nextInt());
// add this line
input.nextLine()
System.out.println("What is the dog's color? ");
my_dog.setColor(input.nextLine());
System.out.println("What is the owner's name? ");
my_dog.setOwner(input.nextLine());
}
}
使用input.next()而不是input.nextLine()将解决此问题。
nextLine()方法返回介绍狗的年龄后按ENTER按钮时被nextInt()跳过的行。
public static void main(String... args) {
Scanner input = new Scanner(System.in);
Dogs my_dog = new Dogs();
System.out.println("What is the dog's name? ");
my_dog.setName(input.next());
System.out.println("What is the dog's age? ");
my_dog.setAge(input.nextInt());
System.out.println("What is the dog's color? ");
my_dog.setColor(input.next());
System.out.println("What is the owner's name? ");
my_dog.setOwner(input.next());
}