gpt4 book ai didi

java - 当我在类中添加 int 属性时,代码停止工作

转载 作者:行者123 更新时间:2023-12-02 03:45:36 25 4
gpt4 key购买 nike

我遇到了一些问题,当我在类中添加 int 属性时,下面的代码停止工作,当询问“希望继续”时代码结束......没有这些行,代码运行良好。有什么问题吗?

public static void main(String[] args) {
ArrayList<Humano> lista = new ArrayList<>();
Scanner input = new Scanner(System.in);
String userInput;
do {
Humano h = new Humano();
System.out.println("Name");
h.setName(input.nextLine());
System.out.println("age");//<-----------
h.setAge(input.nextInt());//<----------this lines causes problems
lista.add(h);
System.out.println("wish to continue?");
userInput = input.nextLine();

} while (!userInput.equalsIgnoreCase("NO"));

人类类

public class Humano {

private String name;
private int age;

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;
}

最佳答案

这里是第一个答案:)

Scanner#nextInt() 方法不会消耗输入的最后一个换行符,因此会消耗下一个可用的 newline() 。最好的解决方法是在使用 nextInt()next()nextFoo( ) 方法。

欲了解更多答案,请查看: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

关于java - 当我在类中添加 int 属性时,代码停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36341698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com