java file int array read -
i want array of integers file .but when array unwanted zeros in array size 10 , there 5 integers in file(18,12,14,15,16). how remove zeros. code is:
import java.io.file; import java.io.ioexception; import java.util.arrays; import java.util.scanner; public class txtfile { public static void main(string[] args) { // todo auto-generated method stub file infile=new file("h:\\documents\\javaeclipseworkplace\\readtextfile\\src\\txt.txt"); scanner in=null; int []contents = new int[10]; int i=0; try { in=new scanner(infile); while(in.hasnextint()){ contents[i++]=in.nextint(); } system.out.println(arrays.tostring(contents)); } catch(ioexception e){ e.printstacktrace(); } finally{ in.close(); } }
}
output is: [18, 12, 14, 15, 16, 0, 0, 0, 0, 0].
this because allocate array of size 10, , values initialized 0 default. read 5 values file, , overwrites first 5 values in array, untouched 0's still there.
you have few options:
you count number of values read file, resize array match, e.g.:
while(in.hasnextint()){ contents[i++]=in.nextint(); } // 'i' contains number read file: contents = arrays.copyof(contents, i); // contents contains 'i' items. system.out.println(arrays.tostring(contents));
you count number of values read file, explicitly print many values, e.g.:
while(in.hasnextint()){ contents[i++]=in.nextint(); } // 'i' contains number read file: (int n = 0; n < i; ++ n) system.out.println(contents[n]);
you use dynamic container arraylist<integer>
, , add values read them. can support number file automagically, e.g.:
arraylist<integer> contents = new arraylist<integer>(); ... while(in.hasnextint()){ contents.add(in.nextint()); } system.out.println(contents);
i recommend third option. flexible , easiest deal with.
Comments
Post a Comment