gpt4 book ai didi

java - TextIO.getln() 没有获取输入?

转载 作者:行者123 更新时间:2023-12-01 10:34:54 25 4
gpt4 key购买 nike

我是 Java 新手。我正在阅读《Java v7 编程简介》一书,发现代码存在问题,如下所示:

public class CreateProfile {

public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
String email;
double salary;
String favColor;

TextIO.putln("Good Afternoon! This program will create");
TextIO.putln("your profile file, if you will just answer");
TextIO.putln("a few simple questions.");
TextIO.putln();

/* Gather responses from the users. */


TextIO.put("What is your name? ");
name = TextIO.getln();
TextIO.put("What is your email address? ");
email = TextIO.getln();
TextIO.put("what is your salary income? ");
salary = TextIO.getDouble();
TextIO.putln();
TextIO.put("What is your favorite color? ");
favColor = TextIO.getln();

/* Write the user's information to the file named profile.txt. */

TextIO.writeFile("profile.txt"); //subsequent output goes to file
TextIO.putln("Name: " + name);
TextIO.putln("Email: " + email);
TextIO.putln("Favorite Color: " + favColor);
TextIO.putf("Yearly Income: %1.2f%n", salary);

/* Print a final message to standard output. */

TextIO.writeStandardOutput();
TextIO.putln("Thank you. Your profile has been written to profile.txt.");

}
}

控制台不会要求我输入最喜欢的颜色,而是直接跳转到写入文件过程。

enter image description here

当我将 favColor 输入语句放在工资之前时,似乎没有问题: enter image description here

谁能解释一下为什么吗?

最佳答案

我的程序也有同样的问题。我通过记住我所学的有关寄存器的一些知识来解决这个问题。

在您的代码中,问题出在这一部分:

salary = TextIO.getDouble();
TextIO.putln();
TextIO.put("What is your favorite color? ");
favColor = TextIO.getln();

当您调用 textio.getdouble() 时,程序仅获取输入的数字并留下文件结尾符号以供下一个 GET 语句检索。因此,在您的代码中,当您调用 textio.getln() 时,它会检索文件结尾并不会保存任何内容,因为 getln 只接受文件结尾字符之前的输入。

解决方案:像这样在 getdouble 之后添加一行

salary = TextIO.getDouble();
TextIO.getln();
TextIO.put("What is your favorite color? ");
favColor = TextIO.getln();

我测试了它,现在可以工作了!

关于java - TextIO.getln() 没有获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823529/

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