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[]).
Code Java:
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.
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.
Code Java:
double marks2[] = new double[5];
for (i=0; i< marks.length; i++)
{
marks[i] = marks2[0];
}
Any suggestions on how to reset the array?
Re: While loop not iterating correctly
Quote:
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];
Quote:
the original array remains filled.
What does "filled" mean?
Re: While loop not iterating correctly
This is the code I tried for making a new array:
Code Java:
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....
Re: While loop not iterating correctly
Quote:
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.
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?
Re: While loop not iterating correctly
Quote:
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.
Re: While loop not iterating correctly
Here is my studentRecords code:
Code Java:
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:
Code Java:
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.
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.
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'
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:
Code Java:
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.
Code Java:
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?
Re: While loop not iterating correctly
Please copy and paste here the full text of any error messages you get.
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.
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.
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):
Code Java:
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.
Code Java:
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++;
}
}
}
}
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 ().
Quote:
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.