Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: While loop not iterating correctly

  1. #1
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default While loop not iterating correctly

    ***While loop now working, just need an argument for a method.***

    I have a text file with 8 lines of information. Each line has an int (UniqueID), a string (name) and 5 doubles (marks). Each item of data is separated bya colon, which I'm using as a delimiter.I've written the following code to read each line and then print out a formatted table of information showing the uniqueID, name and the marks. The marks are to be read as an array(marks[]) and so is the complete table (records[]).
    while (inputStream.hasNextLine() && (numUsed < records.length))
    {
    	uniqueID = inputStream.nextInt();
    	name = inputStream.next();
    	System.out.printf("%7s %8s %-21s", uniqueID, space, name);
     
    	while (inputStream.hasNextDouble() && (i < marks.length))
    	{
    		marks[i] = inputStream.nextDouble();
    		System.out.printf("%9s", marks[i]);
    		i++;
    	}
    	records[numUsed] = inputStream.nextLine();
    	System.out.println(" ");
    	numUsed++;
    }

    When I run the code the first line prints out correctly but the next seven lines print only the uniqueID and name. Can anyone tell me why it runs through the second while loop the first time through but not on subsequent loops.

    p.s. I know the problem isn't in the data file as I use it elsewhere in the program and it runs correctly.
    Thank you in advance for any help.
    Last edited by Rhyssa6; May 18th, 2011 at 09:08 PM.


  2. #2
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    I figured out what the problem is, but not how to fix it. Marks[] is an array of 5 doubles for each student. The array is being filled by the values on the first iteration of the loop so it doesn't read any more values on subsequent iterations.
    I've tried adding a for loop to the end of the first while loop to empty the array but don't know how to do it. Setting marks[i] = null gives me an incompatible types error, while marks[i] = = null gives me the error "not a statement".
    I've also tried making a new array and setting the original array equal to it but it still isn't working; the original array remains filled.
    double marks2[] = new double[5];
     
    for (i=0; i< marks.length; i++)
    {
             marks[i] = marks2[0];
    }
    Any suggestions on how to reset the array?
    Last edited by Rhyssa6; May 14th, 2011 at 11:11 PM.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    tried making a new array and setting the original array equal to it but it still isn't working; the original array remains filled.
    Could you show the code for this. Creating a new array should replace the old one:
    marks = new double[5];
    the original array remains filled.
    What does "filled" mean?

  4. #4
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    This is the code I tried for making a new array:
    double marks2[] = new double[5];
     
    for (i=0; i< marks.length; i++)
    {
    	marks[i] = marks2[i];
    	System.out.println(marks[i]);
    }

    Even though the new array had nothing in it, both of them would be filled with 0.00 values.
    However, this morning the code is working, the array values are being replaced each time the loop iterates (without the new array).

    The code in my assignment still looks exactly the same as what I posted on here yesterday ( I checked it line by line), but now it works - maybe the elves came and did something overnight....

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    Even though the new array had nothing in it, both of them would be filled with 0.00 values.
    I believe that is what the compiler puts in doubles when they are created. A double can only hold numberic values, unlike object reference values which can either be null or have the address of an object.

  6. #6
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    I now have this code working correctly (mostly) - the array reads each line in the text file and prints it out in the required format.
    However I've also tried writing other code for it which has a method 'student' to read just one line of the file and output the details from that one line. I then have another method 'studentRecords' which opens the text file and calls the 'student' method for each line. e.g

    method studentRecords
    open file
    while loop
    {
    read a line
    call 'student' method
    move to next line
    }

    student method
    {
    read line and output desired text
    }

    Because the student method is also opening the file it simply prints the first line of the file each time.

    Is it possible to write the 'student' method so that it will read the next line in the file each time it's called by the 'studentRecord' method? Or must all of the reading from file be done in the 'studentRecords' method?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    Because the student method is also opening the file
    Your pseudo code shows that the StudentRecords method is opening the file.
    Can you post your code? You comments and your pseudo code don't agree.

  8. #8
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    Here is my studentRecords code:
     
    prac Record = new Prac();
     
    public int studentRecords()
    {
                  Scanner inputStream = null;
     
    	try
    	{
    	       inputStream = new Scanner (new FileInputStream("fileReport.txt"));
    	}
     
    	catch(FileNotFoundException e)
    	{
    		System.out.println("Error opening the file fileReport.txt");
    		System.exit(0);
    	}
     
    	int numUsed = 0;
    	int i = 0;
     
    	inputStream.useDelimiter(":");
     
    	while (inputStream.hasNextLine() && (numUsed < records.length))
    	{
     
    		records[numUsed] = Record.student();
    		System.out.println(" ");
    		numUsed++;
    	}
    	return i;
    }

    and here is my student code:
    public String student()
    {
    	Scanner inputStream = null;
     
    	/*try
    	{
    		inputStream = new Scanner (new FileInputStream("fileReport.txt"));
    	}
     
    	catch(FileNotFoundException e)
    	{
    		System.out.println("Error opening the file fileReport.txt");
    		System.exit(0);
    	}*/
     
    	//String line = null;
    	String space = " ";
    	inputStream.useDelimiter(":");
     
    	uniqueID = inputStream.nextInt();
    	name = inputStream.next();
    	System.out.printf("%7s %8s %-21s", uniqueID, space, name);
    	for (int i = 0; i <= marks.length; i++)
    	{
    		while (inputStream.hasNextDouble() && (i < marks.length))
    		{
    			marks[i] = inputStream.nextDouble();
    			System.out.printf("%9s", marks[i]);
    			i++;
    		}
    	}
    		//line = inputStream.nextLine();
    		//inputStream.close();
                                   // return name;
    }

    As you can see I tried commenting out the file opening code in the student file but then I get a 'cannot find symbol variable' error message. I need the inputStream to tell the student method where to get the information but if I add it back in then it just reads the first line each time.
    Last edited by Rhyssa6; May 16th, 2011 at 08:46 AM.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    You need to pass a reference to the file reader class from the method that opens the file to the method that is to read the file. Add a parameter to the student method to pass the inputStream.

    BTW inputStream is almost the name of a java class.

  10. #10
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: While loop not iterating correctly

    It would help if you named your methods according to what they do. Methods do stuff, so should use verbs or verbal phrases, e.g. doSomething(), getFoo(), readBar(). 'student' is a noun - a method called student() tells the reader nothing useful about it. If you're dealing with students, you'd expect to find a Student class holding details for a student, and StudentRecords would be a class dealing with Student objects, or a collection of Student objects.

    If you don't want to go that far, consider calling your 'student' method something like getStudentRecord() or readNextStudent(), and pass in the input stream or reader as a parameter so you have something to read the data from.

    Just sayin'

  11. #11
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    Dlorde, I do usually try to name my methods and objects more reasonably, that was about my 3rd copy of this assignment and I got lazy.
    Norm, I've tried to do what you suggested but I cannot get it to work, my 2 methods fillArray (the calling method) and readStudentRecord keep telling me they cannot find the symbol variables inputStream, hasNextInt(), hasNext() etc.
    Here is the class with my calling method:
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.io.FileInputStream;
     
    public class StudentInfo
    {
    	/**constant for the number of student in the array*/
    	public static final int numRecords = 20;
     
    	TextFile text = new TextFile();
    	Student Record = new Student();
     
    	Student[] records = new Student[numRecords];
    	private int numUsed = fillArray(records);
     
    	public String openFile()
    	{
    		Scanner inputStream = null;
    		try
    		{
    			inputStream = new Scanner (new FileInputStream("../data/Report.txt"));
    		}
     
    		catch(FileNotFoundException e)
    		{
    			System.out.println("Error opening the file ../data/Report.txt");
    			System.exit(0);
    		}
     
    		String line = inputStream.nextLine();
    		return line;
    	}
     
    	/**method to fill the array with student details from the file Report.txt*/
    	public int fillArray(Student[] records)
    	{
    		int i = 0;
    		String line = "null";
    		line = openFile();
    		System.out.println("line is " + line);      //line 42
     
    		while (inputStream.hasNextLine() && (i < records.length))   //line44
    		{
    				records[i] = Record.getStudentRecord();   //line 46
    				i++;
    				System.out.println(" ");
    				line = inputStream.nextLine();     //line 49
    				numUsed++;
    		}
    		return i;
    	}
     
    }

    I get the error 'cannot find symbol variable inputStream' at lines 44 & 49, and 'cannot find symbol method getStudentRecord' at line 46, which I suspect is because that method isn't working due to also not being able to find the variable 'inputStream'.
    The println at line 42 was just to test to see if the getFile method was being called and opening correctly and it is - that line prints the first line of the textfile.
    Here is my code for the Student class, which contains the method I'm trying to call to read one student at a time.
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.io.FileInputStream;
     
    public class Student
    {
    	private int uniqueID;
    	private String name;
    	private double[] marks = new double[5];
    //editted out my constructors here for ease of reading, makes no difference to the compiler
    	public String getStudentRecord()
    	{
    		String line = "null";
    		String space = " ";
    		inputStream.useDelimiter(":");        //line 20
     
    		uniqueID = inputStream.nextInt();       //line 22
    		name = inputStream.next();                //line 23
    		System.out.printf("%7s %8s %-21s", uniqueID, space, name);
    		for (int i = 0; i <= marks.length; i++)
    		{
    			while (inputStream.hasNextDouble() && (i < marks.length))    //line 27
    			{
    				marks[i] = inputStream.nextDouble();        //line 29
    				if (marks[i] < 0)
    				{
    					marks[i] = 0.0;
    				}
    				System.out.printf("%9s", marks[i]);
    				i++;
    			}
    		}
    		return name;
    	}
     
    }

    I get the 'cannot find symbol variable inputStream' at the numbered lines in this method too.
    I've tried every way and place I can think of but cannot get this to work - what am I doing wrong?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    Please copy and paste here the full text of any error messages you get.

  13. #13
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    I can't copy & post from the Task or Build view windows but the error messages are exactly what I posted above.
    In the StudentInfo file:
    cannot find symbol variable inputStream line 44
    cannot find symbol method getStudentRecord() line 46
    cannot find symbol variable inputStream line 49

    and in the Student file:
    cannot find symbol variable inputStream line 20
    " " " " " line 22, 23, 27, 29

    Those are all when I compile the files. If I try to run the program then the message 'cannot find symbol method getStudentRecord at line 46 instudentInfo changes to 'incompatible types, the other messages all remain the same.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    The compiler can NOT find in scope definitions for the variables listed in the error messages.
    Do you understand what in scope means? Code within a pair of {} is in the same scope. If a variable is defined within a pair of {}s it is out of scope outside of those {}s and can NOT be referenced or used.

    Where are those variables defined? You need to add defintions for those variables so the compiler can find them. You must define ALL variables that you use and give them values.

  15. #15
    Junior Member
    Join Date
    Apr 2011
    Posts
    10
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: While loop not iterating correctly

    Thanks Norm, I understand what you mean about the variables being outside the scope of the method. I also had my file opening method wrong. I now have it all working excpet for one thing. When I call the getStudentRecord method it wants something in the brackets but nothing I try works.
    Here is the StudentInfo code (the calling code):
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.io.FileInputStream;
     
    public class StudentInfo
    {
    	/**constant for the number of student in the array*/
    	public static final int numRecords = 20;
     
    	TextFile text = new TextFile();
     
    	//private int numUsed = fillArray(records);
     
    	public static Scanner openTextFileInput(String fileName)
    	{
    		Scanner inputFile = null;
     
    		try
    		{
    			inputFile = new Scanner (new FileInputStream(fileName));
    		}
     
    		catch(FileNotFoundException e)
    		{
    			System.out.println("Error opening the file ../data/Report.txt");
    			System.exit(0);
    		}
     
    		return inputFile;
    	}
     
     
    	/**method to fill the array with student details from the file Report.txt*/
    	public static void fillArray(Scanner inf )
    	{
    		Student[] records = new Student[numRecords];
    		Student Record = new Student();
    		int i = 0;
    		String line;
     
    		while (inf.hasNextLine() && i < records.length)
    		{
    			line = inf.nextLine();
    			System.out.println(line);
    			records[i] = Record.getStudentRecord();          //line 48
    			System.out.println("records " + i + records[i]);
    			i++;
    			System.out.println(" ");
    		}
    	}
    }
    The error message is at line 48 and changes depending on what I put in the brackets.
    If the brackets are empty the message is "getStudentRecord in Student cannot be applied to ()".
    Looking at the getStudentRecords code I'd think it wants an input but that gives me either an incompatible types error or a cannot find symbol variable error, as does putting in a String.
    import java.io.PrintWriter;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.io.FileInputStream;
     
    public class Student
    {
    	private int uniqueID;
    	private String name;
    	private double[] marks = new double[5];
     
    	public void getStudentRecord(Scanner inf)
    	{
    		String space = " ";
    		inf.useDelimiter(":");
     
    		uniqueID = inf.nextInt();
    		name = inf.next();
    		System.out.printf("%7s %8s %-21s", uniqueID, space, name);
    		for (int i = 0; i <= marks.length; i++)
    		{
    			while (inf.hasNextDouble() && (i < marks.length))
    			{
    				marks[i] = inf.nextDouble();
    				if (marks[i] < 0)
    				{
    					marks[i] = 0.0;
    				}
    				System.out.printf("%9s", marks[i]);
    				i++;
    			}
    		}
    	}
     
    }

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: While loop not iterating correctly

    Look at the definition for the getStudentRecord method. Does it take any args? What data type?

    You need to put a arg in the ().

    gives me either an incompatible types error or a cannot find symbol variable error
    If you get errors, please copy and paste the FULL text of the error message here.

  17. The Following User Says Thank You to Norm For This Useful Post:

    Rhyssa6 (May 20th, 2011)

Similar Threads

  1. I can't get this loop to work correctly
    By Nismoz3255 in forum Loops & Control Statements
    Replies: 1
    Last Post: February 27th, 2011, 04:20 PM
  2. Replies: 3
    Last Post: November 9th, 2010, 01:19 PM
  3. Need help getting things to loop correctly
    By egruna2 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: September 9th, 2010, 04:53 PM
  4. [HELP] Iterating through a jagged edged array
    By AlexBeer in forum Collections and Generics
    Replies: 2
    Last Post: April 12th, 2010, 06:33 AM