gpt4 book ai didi

java - FileWriter 未接收所有输入和神秘的悬空换行问题

转载 作者:行者123 更新时间:2023-12-01 21:14:35 25 4
gpt4 key购买 nike

我正在尝试编写一个Java程序,其中用户指定他们想要输入多少“学生记录”,然后是学生的姓名、年龄和GPA,然后将其存储为文本。然而,我的文本有问题,不包括所有输入的数据和一个我无法摆脱的神秘的悬空换行符。这是我的程序:

import java.io.*;
import java.util.Scanner;

public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:\\Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.nextLine();
input.nextLine();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
next = input.nextLine();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}

这是示例输入和输出来说明我的问题:

run:
How many student records would you like to enter: 3
Enter Name: Jon
Enter Age: 20
Enter GPA: 3.4
Enter Name: Bill

Enter Age: 24
Enter GPA: 3.6
Enter Name: Ted

Enter Age: 34
Enter GPA: 3.9

This is the produced text file:
20
3.4
Bill
24
3.6
Ted
34
3.9

为什么它不存储输入的名字?为什么第一个条目中没有换行符,但其他条目中有换行符?

最佳答案

问题在于,当您需要使用 next() 时,您却使用了 nextLine()。我假设您将第二个 input.nextLine() 放在那里,因为您最初遇到一个问题,它会打印出“Enter Name:”,然后立即“Enter Age:”。 nextLine() 告诉你的程序跳过那里的任何内容,而不是等待它。此范例对您的任何条目都有效的原因是您将 next = input.nextLine() 放在循环的底部。这是一个修复:

package createfile;
import java.io.*;
import java.util.Scanner;
public class CreateFile {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
FileWriter fwriter = new FileWriter("c:Students.dat");
PrintWriter StudentFile = new PrintWriter(fwriter);
String name = " ";
String next = " ";
int age = 0;
int hm = 0;
double gpa = 0.0;
System.out.print("How many student records would you like to enter: ");
hm = input.nextInt();
for (int x = 1; x <= hm; x++) {
System.out.print("Enter Name: ");
name = input.next();
System.out.print("Enter Age: ");
age = input.nextInt();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
StudentFile.println(name);
StudentFile.println(age);
StudentFile.println(gpa);
}
StudentFile.close();
System.exit(0);
}
}

您也可以将 input.nextLine() 移至 name=input.nextLine() 上方,它会产生相同的效果。

关于java - FileWriter 未接收所有输入和神秘的悬空换行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40470547/

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