【问题标题】:Why are two digits being printed out rather than one?为什么打印出来的是两位而不是一位?
【发布时间】:2013-12-05 22:35:47
【问题描述】:

在编译和运行这个程序时,会创建一个包含以下参数的文件:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 20]20

我不明白数组关闭后额外的 20 来自哪里。如何删除它?是什么原因造成的?

程序正在创建一个 .txt 文件并输入一个数组。最后一位被修改为 20,但由于某种原因,另外 20 被添加到整个数组之外。代码如下:

public static void main(String[] args) throws IOException 
{
    int[] a = {1,2,3,4,5,6,7,8,9,10};

    File file = new File("text.txt");                    
    if (!file.exists())                   
    {
        file.createNewFile();
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());     
    BufferedWriter bw = new BufferedWriter(fw);         

    bw.write(" " + Arrays.toString(a));             
    bw.close();                         

    System.out.println("Done!");                   

    StringBuilder contents = new StringBuilder();           
    file = new File("text.txt");

    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) 
    {
       contents.append(line);
    }

    String[] numbers = contents.toString().split("10");

    try {
        numbers[numbers.length - 1] = String.valueOf(Integer.parseInt(numbers[numbers.length - 1]) - 1);
    } catch (NumberFormatException nfe) { }

    FileOutputStream fos = new FileOutputStream(file);          
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));

    for(String number : numbers)
    {
        out.write(number + 20);
    }

    out.close();

}

【问题讨论】:

    标签: java arrays digits


    【解决方案1】:

    很可能,您的意图是这样

    String line20 = line.replaceAll("\\b20\\b", "10");
    

    \\b 确保 20 是单词,而不是单词的一部分。


    你的“数字”是一个字符串。当你添加 20 行 "text" 时,你会得到 "text20"

    当你除以“10”时,你会得到两个字符串

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 
    ]
    

    所以当你在每个之后添加“20”时

    [1, 2, 3, 4, 5, 6, 7, 8, 9, 20
    ]20
    

    【讨论】:

    • 除了将数据类型从字符串更改为其他内容之外,没有其他方法可以删除这 20 个吗? (顺便说一下,这也需要我更改修改最后一位数字的结构)
    • 有没有办法拆分并只接收一个字符串?
    • @user3071133 有没有办法把一根香蕉劈开,只得到一根?
    • @user3071133 您要查找的术语是replace 10 for 20。请参阅我的回答。
    • 当我将 Split 替换为 ReplaceAll 时,我似乎无法在代码中正确实现替换。
    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    相关资源
    最近更新 更多