user3071133
user3071133

Reputation: 55

Why are two digits being printed out rather than one?

Upon compiling and running this program, a file is created with the following parameters:

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

I do not understand where that additional 20 comes from after the array is closed. How can I remove it and what is causing it?

The program is creating a .txt file and typing out an array. The last digit gets modified to 20 but for some reason another 20 gets added outside of the whole array. Here is the code:

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();

}

Upvotes: 0

Views: 94

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

Most likely, what you intended was this

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

The \\b ensures the 20 is word, not part of a word.


Your "number" is a String. When you add 20 line "text" you get "text20"

When you split by "10" you get two Strings

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

so when you add "20" after each of these you have

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

Upvotes: 2

Related Questions