java - Infinite loop when trying to read and create a file -
this java code compiles. when ran program, lasted long time , didn't results, , said runofoutspace, guess fell infinite loop, cannot figure out why.
import java.util.*; import java.io.*; public class exercise3{ public static void main (string[] args){ file infile = new file(args[0]); file outfile = new file("ex3.txt"); try { scanner scan = new scanner(infile); arraylist<string> readfile = new arraylist<string>(); string findword = args[1]; string replaceword = args[2]; while(scan.hasnextline()) { readfile.add(scan.nextline()); } //system.out.println(readfile); (int i=0; i<readfile.size();i++) { string n = readfile.get(i); n = n.replaceall(findword,replaceword); readfile.add(i,n); } printwriter output = new printwriter(outfile); (int i=0; i<readfile.size();i++) { output.println(readfile.get(i)); } output.close(); scan.close(); } catch (filenotfoundexception e){ system.err.println("file not found."); } } }
the issue :
(int i=0; i<readfile.size();i++) { string n = readfile.get(i); n = n.replaceall(findword,replaceword); readfile.add(i,n); }
you incrementing size of arraylist, inside for-loop. readfile.add(i,n); . size of readfile gets incremented on each iteration of loop, loop condition never evaluate false.
when add new element @ index i, former element @ index shifted right. won't replaced.
Comments
Post a Comment