hello !

im trying to read few numbers from a file and but each line of numbers in diffrent array

now i can read the numbers but in one array

any help

here is the code

public static void main(String[] args) throws IOException {
      
        File number = new File ("numbers.txt");
        number.createNewFile();
        Scanner in = new Scanner(number);
        int [] no = new int [12];
        int count =0; // count for number of elements in the file
        
         while (in.hasNextInt())
        { 
           no [count] = in.nextInt();
          count++;
        }
        
        for (int i=0 ; i<no.length;i++){
              System.out.println(no[i]);
    
        }
     }

}

Recommended Answers

All 9 Replies

Can you explain what your problem is?
Does the posted code work as you want it to?
Do you get errors? If so, please post the full text of the error message.

my problem is i need to read from a file some number and put each line of numbers in different array (but now this code put all the lines in one array) and there is no errors
thank u

Maybe use an array of arrays? int[][] no where no[0] contains the array for the first line, no[1] contains the array for the second line etc

I think you can do this to help your case.

while(scanner has lines){
	//get line into a string variable from scanner
	Scanner secondScanner = new Scanner(line);
	while(secondScanner has integers){
		//read numbers into array here.
	}
        secondScanner.close();
}

james : i cant use two dimension array cuz the number of digits in each line are different

adarshcu : i cant understand what your do can u simplfy more

number of digits in each line are different

That is no problem. Each subarray in a two dim array can be a different size.

james : i cant use two dimension array cuz the number of digits in each line are different

I didn't say 2D array, because there's not really any such thing in Java. I said array of arrays, which is what Java has. The "inner" arrays don't have to be the same size. For example it's perfectly valid to have:

int[][] a = new int[3][]; // array of 3 arrays...
      a[0] = new int[1];        // first is 1 element
      a[1] = new int[5];        // second has 5 elements
      a[2] = new int[999];      // third is a lot bigger

so this is just what you need!

I read a line into a String. Then use an another Scanner to read the line and get the numbers from that line and store it in an array for each line or as James says, an array of arrays.

thank u guys u really helped me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.