I am new to java and many of the nuances to this language.

For my class assignment we need to finish our methods which I have already done and do not want any help with. What I need help with is reading the data from the file with in "main".

I have done some google searches on this but it is still kind of vague and not making sense.

What I want to do is read two points x and y (int values) from a text (notepad) file. So say the test file has the following values

0 1
1 2
2 3

My insert method (below) wants to read these from the file and insert them in to my two arrays, one for x and one for y.

void addPoints(int x, int y)  {
    int cur = 0;
    xPts[cur] = x;
    yPts[cur] = y;
    cur++;
}

My first thought is put something together like the below code

String message;
 message = stdin.readLine();
 int myVal = Integer.parseInt(message); // convert message to int

 while( message != null )  
  {   addPoints()   }

My problem with this is that my function is looking for two values where I want to see two values.

I guess I could change my function to addYPoint and addXPoint and alternate the inserting since x and y will always have a value.

Added later...
Or I could do a two dimensional array? pts[][] Now that i think more about it I think this would be best?

But my real issue is the main function and reading the data from the test file.

Once I figure this part out, my next question is how do I input the file as my input from compiling?

My thought would be the following command...

java Homeworkfile < testfile

Can some one please point me in the right direction? I feel like I am close and want to make sure my methods works correctly.

In the past most of the time these main functions to test my files were provided for us. Hence me not really understanding this portion of the excitement known as JAVA.

Thanks in advance.

Recommended Answers

All 14 Replies

perhaps you are over-complicating this problem...

i suggest you look at the Class java.io.File, which should be a lot better than reading files from stdin (i have never even tried that).

adding your points, you seem to be over-complicating too. as long as you get each line at a time you will have x, y to satisfy your parameters.

good luck

Well for reading a file I use BufferedReader:

String fileName="C:/folder1/file.txt"
BufferedReader reader = new BufferedReader( new FileReader(fileName) );
String line = reader.readLine();
while(line!=null) {
   System.out.println(line);

    line = reader.readLine();
}

First you need to read the first line which happens outside the loop.
Then in order to enter the loop and continue, what you read should be not null. At the end of the loop after you have finished with all the calculations you read the next. Again you check to see if it is not null in order to continue. At the end of each loop you read the next line, so when you go at the begining you need to check if it is null or not in order to continue.
When you have reached the End Of the File the reader.readLine(); will return null so the while loop will exit.

Now after you have read the line here is an example on how to proceed

String line = "2 3";
String [] tokens = line.split(" ");
//tokens[0] has value "2"
//tokens[1] has value "3"

addPoints(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]));

As for question about entering parameters, if you run the program like this:

java MainClass C:/folder1/file.txt

Then inside the main, the args array will have size 1 and the args[0] will have the input you gave:

public static void main(String[] args) {
		String file = args[0];
                System.out.println(file);
	}

Of course all the necessary checks should be made. Example:

public static void main(String[] args) {
    String file=null;
    if (args.length>0) {
          file = args[0];
          System.out.println(file);
   } else {
        return;
   }
	}

...
I always make these more difficult then they need to be, but it is starting to come together. Slowly, but seems to be getting there. Main is the easy part of programming, the methods are the tricks.

...
Thank for being so detailed on many of the tests.

I believe the following will be the most helpful,

String fileName="C:/folder1/file.txt"
BufferedReader reader = new BufferedReader( new FileReader(fileName) );
String line = reader.readLine();
while(line!=null) {
   System.out.println(line);

    line = reader.readLine();
}

Off to jury duty, then come home to test this out.

Ok, that seems to work for the read line but now my problem is inserting the two values into my two arrays.

I am trying a bunch of things but how do I enter the following, but keep getting non static references. I tried eliminating the method and inserting from the readline, but as I mentioned I keep getting non statis to static references.

1 2
2 3
3 4

into X[] and Y[]

so it looks like
X[1] [2] [3]
Y[2] [3] [4]

once I get past this I feel my methods will work. Any help would be appreciated.

Some things I have tried...

while(line != null) {
            line = reader.readLine();
            //int W = Integer.parseInt(line.substring(0,1));
            //int xVal = Integer.parseInt(tokens[0]);
            //int xVal = Integer.parseInt(tokens[1]);
            // addPoints(W);
            // yPts[].addPoints(W);
            int x = Integer.parseInt(line.nextToken());
            int y = Integer.parseInt(line.nextToken());
            xPts[cur] = x;  // these are created as public arrays earlier.
            yPts[cur] = y;
            cur++;
         }
while(line != null) {
            line = reader.readLine();
            //int W = Integer.parseInt(line.substring(0,1));
            //int xVal = Integer.parseInt(tokens[0]);
            //int xVal = Integer.parseInt(tokens[1]);
            // addPoints(W);
            // yPts[].addPoints(W);
            int x = Integer.parseInt(line.nextToken());
            int y = Integer.parseInt(line.nextToken());
            addPoints(x,y);
         }

  private void addPoints(int x, int y)  {
    int cur = 0;
    xPts[cur] = x;
    yPts[cur] = y;
    cur++;
}

I don't know what the name of your class is, but I do think I know why you are getting static reference errors.

You are in a static method, main (look at the declaration of the method - it says static), and you are probably trying to put things into an array you declared in your class body (so inside of your class, but not within any method) that is not declared as static. By default, anything that is not declared as static is automatically declared by the compiler as public, and therefore is not static. Consider the purpose of static-ness (static methods or static variables) to begin with. Static methods and variables have one copy for the entire class, whereas every time you create a new Object, that Object gets a new copy of each of the non-static class variables. So with that in mind, consider that your static main method cannot do anything with non-static variables, since you have to make an Object for them to even exist! And with that in mind, read this for any more information, http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Also, as far as your code in general: Your input file has two things per line, an X and a Y. Using a 2-D array is not a bad idea at all. You should use the Scanner class's nextInt() method to read in each X and Y. The way the nextInt() method works, it would just give you whatever the nextInt was in the file. So all you need to do is

Scanner scanner = new Scanner(yourFileName);
array[0][0] = scanner.nextInt(); //gives you the first X
array[0][1] = scanner.nextInt(); // gives you the first Y

I'll let you extrapolate on that to read in the rest of your values using a loop into the array. Get rid of the BufferedReader - it doesn't have the functionality you really want in this case - and replace it with Scanner.

are you getting compile or runtime errors?

if you are getting compile errors you are probably using static variables / methods in a non-static way or the other way around. just have a look at how you have defined each of your methods / variables.

the second block of code won't work because cur is always 0.

EDIT: by "cur is always 0" i am referring to the array position

while(line != null) {
            line = reader.readLine();
                       //int W = Integer.parseInt(line.substring(0,1));
                       //int xVal = Integer.parseInt(tokens[0]);
                      //int xVal = Integer.parseInt(tokens[1]);
                       // addPoints(W);
                       // yPts[].addPoints(W);
            int x = Integer.parseInt(line.nextToken());
            int y = Integer.parseInt(line.nextToken());
            xPts[cur] = x;  // these are created as public arrays earlier.
            yPts[cur] = y;
            cur++;
         }

"line" is a String. Where did you get the nexToken thing? Have you looked the example with spilt method?

Before I go and try and put it in a two dimensional array I am trying to put it into a simple array and print to see if my values get into my array, but of course I was not able to.

Can some one help me see what I am doing wrong?

Off to Jury duty again, once I finish I will be back testing. Thanks in advance for all your help.

import java.util.Scanner;
   import java.io.File;

    public class test {
   
       public static void main( String [ ] args )  {
         int cur = 0;    			// current number of points
         int temp[] = new int[10];   //file only has 6 int's on the file
      
       
         String fileName ="C:/MyFile.txt";  //myfile
         Scanner scanner = new Scanner(fileName);
         while(scanner.hasNextInt()) {
            int x = scanner.nextInt();
            temp[cur] = x;
         
         }
         int i;
         for (i=0;i<10;i++){
            System.out.println("value " + temp[i]);
            //System.out.println("value " +i + yPts[i]);
         }
      }	
      
   }

PS I noticed why cur would always be 0 in that function, should declare that out side the method. Thanks.

Well first of all you need to declare Scanner like this if you want to read from a file:

String fileName ="C:/MyFile.txt";  //myfile
      
      //Scanner scanner = new Scanner(fileName);

      Scanner scanner = new Scanner(new File(fileName));

With your way, I tried to do scanner.next() and it returned the fileName, meaning it returned the String you put at the constructor not the elements of the file.

Also in the while, you forgot to increment the cur value:

while(scanner.hasNextInt()) {
         int x = scanner.nextInt();
         temp[cur] = x;
      
         [B]cur++;[/B]
      }

I would suggest to add an extra check at the whill loop in case the file is too big:

while ( (scanner.hasNextInt()) && (cur<temp.length) ) {

Also at the for-loops it is best to use the length attributes. If you change the length of the array, you don't need to search and change the entire code for all the loops:

int i;
      for (i=0;i<temp.length;i++){

Yeah sorry, I probably should have told you to look at the Scanner javadoc, since I could not remember what the exact constructor was. I really meant to point you in the direction of Scanner though, not give you exact code, although in this case I should have looked it up or mentioned that I wasn't sure. Anyway, like javaAddict said, you can use a File object to do it properly. That and other ways are shown here

Well first of all you need to declare Scanner like this if you want to read from a file:

String fileName ="C:/MyFile.txt";  //myfile
      
      //Scanner scanner = new Scanner(fileName);

      Scanner scanner = new Scanner(new File(fileName));

With your way, I tried to do scanner.next() and it returned the fileName, meaning it returned the String you put at the constructor not the elements of the file.

How do I get get the contents of my file into the array, instead of fileName?

What am I doing wrong, or point me in the right direction

The other stuff made a lot of sense. Thanks.

As for the Scanner stuff, there seems to be 40 ways to read from a file (buffered reading, scanning, file reader, etc...)

I will use any as long as I can print the array with the contents of my file. Once I get that then I can test my methods and finish this stupid thing.

PS Serving jury on a civil trial can be brutal.

with the following code I get one value returned in my array.

import java.util.Scanner;
   import java.io.File;
   import java.io.FileNotFoundException;
   import java.lang.Object;
   import java.io.IOException;

	
    public class test {
   
       public static void main( String [ ] args ) throws IOException {
         int cur = 0;    			// current number of points
         int temp[] = new int[10]; 
      
       
         String fileName ="C:/MyFile.txt";  //myfile
         //Scanner scanner = new Scanner(fileName);
         Scanner scanner = new Scanner(new File(fileName));
      
         while((scanner.hasNextInt()) && (cur<temp.length)) {
            int x = scanner.nextInt();
            temp[cur] = x;
            
         }
         int i;
         for (i=0;i<temp.length;i++){
            System.out.println("value " + temp[i]);
            //System.out.println("value " +i + yPts[i]);
         }
      }
      
   }

the values in my file are ..

1 1
2 2
3 3

When I print my array i get
3
0
0
0
0
0

Read carefully my latest post

duh...

Once I incremented cur, I was able to print out the values.

Thank you again for your patience and all your help.

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.