【问题标题】:How to replace string with int in button action?如何在按钮操作中用 int 替换字符串?
【发布时间】:2017-08-24 20:44:36
【问题描述】:

我在按钮操作中有这段代码:

String text = jTextField18.getText();
int x = Integer.parseInt(text);

String text = jTextField18.getText();
int x = Integer.parseInt(text);
try {
    FileReader fr1 = new FileReader("Name.txt");
    BufferedReader br1 = new BufferedReader(fr1);
    String str = null;
    for (int i = 1; i <= x; i++) {
        str = br1.readLine();
    }
    br1.close();

    jTextField13.setText(str);

但是当我按下按钮时,jTextField13"",没有任何文字。为什么?

【问题讨论】:

  • str=br1.readLine(); 更改为str += br1.readLine() + " ";
  • 不,它仍然不起作用
  • 好的,那么您将需要创建并发布您的minimal reproducible example,这是一个可编译和可运行的小程序,我们可以对其进行测试和修改,这样我们就可以实际了解什么不工作以及为什么。这将为您提供快速获得体面答案的最佳机会。

标签: java string for-loop filereader


【解决方案1】:

这段代码

FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1 = new BufferedReader(fr1);
String str = null;
for (int i = 1; i <= x; i++) {
    str = br1.readLine();
}
br1.close();

打开文本文件,逐行读取,但只保留最后一行。 如果此行为空,则 str 也将为空。

相反,你可以

  • 要么做

    String str = "";
    for (int i = 1; i <= x; i++) {
        str += br1.readLine() + "\n";
    }
    br1.close();
    
  • 或者仅仅依赖流(在 Java 8 上):

    String str = br1.lines().collect(Collectors.joining("\n"));
    br1.close();
    

注意:除此之外,您还可以使用 try-with-resources:

try (
     FileReader fr1 = new FileReader("Name.txt");
     BufferedReader br1 = new BufferedReader(fr1)) {
    // stuff above
}

如果这仍然没有改变任何东西,您可以在循环期间添加调试输出。分配str之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多