gpt4 book ai didi

java - 通过文件写入器打印所有值

转载 作者:行者123 更新时间:2023-12-02 07:23:04 26 4
gpt4 key购买 nike

我想打印用户将输入的所有字母,但问题是,我的程序仅打印用户将输入的最后一个值,并且仅将最后一个值记录在 Ascii.txt。它应该看起来像这样

例如:用户输入A,B,c,C

我也想删除逗号,但我不能:(

“Ascii.txt”中的输出应该是:

A = 65
B = 66
c = 99
C = 67

请不要笑我,因为我还是一名学生,而且是编程新手,非常感谢

import java.io.*;

public class NewClass2{
public static void main(String args[]) throws IOException{



BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Please Enter letters separated by comma: ");

String str = buff.readLine();
for ( int i = 0; i < str.length(); ++i )
{
char c = str.charAt(i);
int j = (int) c;
System.out.println(c +" = " + j);
{
try
{
FileWriter fstream = new FileWriter("Ascii.txt");
BufferedWriter out = new BufferedWriter(fstream);

out.write(c+" = "+j);
out.close();

}catch (Exception e){
}
}
}
}
}

最佳答案

问题是您要关闭并重新打开要转储到 ASCII 文件的每个字符的 FileStream。因此,在写入字符之前您的文件将被清空。只需将流的创建和关闭移到循环之外即可。

    BufferedReader buff = new BufferedReader(new  InputStreamReader(System.in));
System.out.println("Please Enter letters separated by comma: ");

String str = buff.readLine();
BufferedWriter out = null;
try
{
FileWriter fstream = new FileWriter("Ascii.txt");
out = new BufferedWriter(fstream);
for ( int i = 0; i < str.length(); ++i )
{
char c = str.charAt(i);
int j = c;
System.out.println(c + " = " + j);

out.write(c + " = " + j);

}
}

catch ( Exception e )
{
;
}
finally
{
if ( out != null )
{
out.close();
}
}

为了从输出中删除逗号,我建议使用 String.split() :

    //...          
String[] splittedStr = str.split(",");
for ( int i = 0; i < splittedStr.length; i++ )
{
if ( splittedStr[i].length() > 0 )
{
char c = splittedStr[i].charAt(0);
int j = c;

out.write(c + " = " + j);
}
}
//...

关于java - 通过文件写入器打印所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13936585/

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