File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Read an integer line by line Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Read an integer line by line" Watch "Read an integer line by line" New topic
Author

Read an integer line by line

krishna kumar.s
Greenhorn

Joined: Oct 01, 2011
Posts: 19
I have a text file with some row of integers .
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
I want to transfer this as it is to a double dimension array, i used below programme , i am unable to read line by line and store in seperate rows ,all are stored in one row. Please help.

Stefaan Dutry
Ranch Hand

Joined: Sep 17, 2010
Posts: 32

Hello,

One way to do this is to split your input in lines first and then process each line into an array of integers.

You can use the hasNextLine() and the nextLine() methods from Scanner for this.

Also notice that Scanner has a Constructor which accepts a String as parameter.
You can use this to further process each line.

On a sidenote i see you are using a fixed size array for this.
You might want to use an ArrayList instead and then move from this list to an int-array (that way you can declare your array with the size of the list).

Hope this helps.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7892
    
  21

krishna kumar.s wrote:I have a text file with some row of integers .
I want to transfer this as it is to a double dimension array, i used below programme , i am unable to read line by line and store in seperate rows ,all are stored in one row. Please help.

You don't really need a Scanner for this, a BufferedReader will do just as well (and will almost certainly be faster).
The general pattern for a loop to read lines is:orif you prefer self-contained loops.
(NOTE: the inner brackets in the while expression are important)

The only other major thing I can see is that you don't need int[][] num = new int[1000][1000];
int[][] num = new int[1000][]; will do just as well and will take up 1,000 times less space (initially).

Other than that, have a look at String.split(). I think you'll find it's exactly what you want; but I'll leave you to work out the rest. This is homework after all .

HIH

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Stefaan Dutry
Ranch Hand

Joined: Sep 17, 2010
Posts: 32

Winston Gutkowski wrote:Other than that, have a look at String.split(). I think you'll find it's exactly what you want


I don't know if I agree with you on that, although it does return an array, it's an array of Strings, which need to be parsed to integers one by one again.
If you use Scanner again with the line, you can use the hasNextInt() and nextInt() methods to give you integers instead of Strings.
krishna kumar.s
Greenhorn

Joined: Oct 01, 2011
Posts: 19
Thanks for both the replies , I have done few changes according to you suggestions, I am getting an exception.Exception in thread "main" java.lang.NullPointerException
at Exercise18.main(Exercise18.java:19)
the new code is

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class Exercise18 {

/**
* @param args
*/
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
int[][] values =readfile();
int depth = values.length - 2;

System.out.println(depth);
}



public static int[][] readfile()
{
int[][] num =null ;


int i,j;
int l=0;
i=0;
j=0;
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("\\nametri.txt")));


while(s.hasNextLine())
{
String str=s.nextLine();
while(str.length()<1)
{
num[i][j]=Integer.parseInt(str.substring(l, l+2));
str=str.substring(l+2, str.length()+1);
l=l+2;
j++;
}
i++;
}



} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


finally {
if (s != null) {
s.close();
}
}


return num;


}


}
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Please UseCodeTags. You can see how the code looks in your initial post when surrounded with code tags.

You are receiving the exception since the num array variable is initialized to null. You have to initialize it with a size before using it. But see that you are computing the value of the depth by using the array length - 2.

So if you initialize like below you will always get the depth as 48




Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7892
    
  21

Stefaan Dutry wrote:I don't know if I agree with you on that, although it does return an array, it's an array of Strings, which need to be parsed to integers one by one again.
If you use Scanner again with the line, you can use the hasNextInt() and nextInt() methods to give you integers instead of Strings.

You may be right, although I suspect there's no "right" solution for this particular problem .

I happen to loathe Scanner, so I'm admittedly biased, but from what I understand you pay quite a penalty for all that "scanning", so if you redirect your Scanner from console input to some hefty file, you may take a performance hit. Furthermore, I'm pretty sure you'll still need hasNextLine() to deal with the newlines in the input.

The advantage of dealing with the input in lines and using String.split() is that you know how big your int[] needs to be when you create it, viz:and then your loop becomes simply:although I totally agree that num would be better as an ArrayList.

Winston
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
although I totally agree that num would be better as an ArrayList.

Yes... or as a Map<Integer,List<Integer>> - you can have the line numbers in which you read the list of integers as the keys
Stefaan Dutry
Ranch Hand

Joined: Sep 17, 2010
Posts: 32

Winston Gutkowski wrote:The advantage of dealing with the input in lines and using String.split() is that you know how big your int[] needs to be when you create it

This creates exact size primitive int arrays from a row:
krishna kumar.s
Greenhorn

Joined: Oct 01, 2011
Posts: 19
Thanks everybody for their valuable suggestion , but I have done in a diffrent novice way.


I got every thing converted to double dim array. Thanks once again for all the help.It took 1 day for me ,but finally when I got the correct output I danced like anything.
Stefaan Dutry
Ranch Hand

Joined: Sep 17, 2010
Posts: 32

Glad to hear you got it working.

Just keep in mind that your code will only work if the numbers are formatted as 2 digits seperated by a single char.

This is perfectly fine for a learning exercise ofcourse.
In real life applications you want to make sure that you foresee subtle input changes so you don't have to rewrite half your code.
( Trust me, there are plenty of real life applications that are written equaly brittle and it's not fun to have to go through the code to fix it everywhere when input is suddenly a bit larger )

Other than that:

Congratulations on your learning success.
krishna kumar.s
Greenhorn

Joined: Oct 01, 2011
Posts: 19
Thanks a lot, any suggestion to improve my code are welcome , suggestion for any books to read are highly appreciated.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39053
    
  23
There is no such thing as a double-dimension array; it is an array of arrays.
That means you can set the size of each array as you go. No need to allocate 100 × 100 memory spaces. You would have to allocate one space for each line in the file to the outer array
int[][] numbers = new int[123][];
Now you can work out from the lengths of the Strings how large each member array is
numbers[3] = new int[4];
Now you have to initialise each int.
 
GeeCON Prague 2014
 
subject: Read an integer line by line