Hi guys,
below I make one program to read in one column the strings and the second column the int:
import java.io.File; import java.util.Scanner; public class Main { private Scanner x; public void openFile(){ try{ x=new Scanner(new File("myfile.txt")); } catch (Exception e){ System.out.println("Could not find file"); } } public void readFile(){ int loop=0; do{ x.hasNext(); String a= x.next(); int b=x.nextInt(); System.out.printf("%s %s\n",a,b); loop++; }while (loop<10);} public void closeFile(){ x.close(); } }
The file includes 10 lines and 2 columns and is like this:
abc 12
def 234
rrt 333
..
..
..
Now what I need is to sum all int of the 2 column. So I try to make some small changes to :
import java.io.File; import java.util.Scanner; public class ReversePartA { private Scanner x; public void openFile(){ try{ x=new Scanner(new File("myfile.txt")); } catch (Exception e){ System.out.println("Could not find file"); } } public void readFile(){ int j=0; int sum=0; int loop=0; for(j=0; j<=10; j++){ x.hasNext(); String a= x.next(); int b=x.nextInt(); sum +=b; }System.out.println(sum);} public void closeFile(){ x.close(); } }
the results of sum from this program is crazy. Any ideas?