gpt4 book ai didi

java - 从 txt 文件名(一个单词)和(整数)中读取输入。将包含年龄和姓名的列表写入输出文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:20 26 4
gpt4 key购买 nike

完成后输出应该是:

15    Michael
16 Jessica
20 Christopher
19 Ashley
etc.

我对此不太擅长,并且希望获得有关如何让 int 和字符串逐行打印的任何输入。我避免使用数组方法,因为我总是在数组方面遇到困难。谁能告诉我我是否走在正确的轨道上,以及如何正确解析或类型转换整数,以便可以将它们打印在输出文件的一行上?我已经为此工作了几天,非常感谢任何帮助!这是我到目前为止所拥有的。

import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;

Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();

System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();


Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));

}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;

while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();

}

}

这是我的错误消息:

Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)

最佳答案

text = inputStream.nextLine(); 将读取包含姓名和年龄的整行文本。假设输入文件中每一行的格式都是年龄名称,您可以执行以下操作将每一行文本解析为所需的值。请注意,这不能与您的其余代码一起立即使用。只是一个指针:

text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];

关于java - 从 txt 文件名(一个单词)和(整数)中读取输入。将包含年龄和姓名的列表写入输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26941600/

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