Java Java: Fix Error & Read File Args to Variables

  • Thread starter Thread starter Sam032789
  • Start date Start date
  • Tags Tags
    Java
AI Thread Summary
The discussion focuses on reading a file line by line in Java and assigning values to variables. The initial code attempts to read a file named "exams.dat" and parse its contents into variables, but an error arises from the condition "if (strLine == expectedArg)", which is incorrect. Suggestions include using `FileReader` instead of `FileInputStream` for simplicity, as well as the unnecessary wrapping of `FileInputStream` with `DataInputStream` and `BufferedReader`. To properly parse the line, it is recommended to use the `split` method on the string, which tokenizes the line into an array of strings based on a specified delimiter. This allows for checking the number of columns and assigning values to the variables accordingly. The length of the resulting array can be accessed to ensure the correct number of arguments is processed. Overall, these adjustments will streamline the code and resolve the parsing issue.
Sam032789
Messages
11
Reaction score
0
Hello, I am just starting to learn Java. I have a small file that needs reading in, line by line, with different arguments. Such a line looks like this:

Code:
123 Midterm .25 100
456 TakehomeExam .25 200
0 Quiz03 .10 25
1 Final .40 100

I need to read these in as separate variables. I already have part of my code:

Code:
import java.io.*;

public class Program {
	public static void main(String args[]) {
		double id = 0.0;
		String label = "";
		double weight = 0.0;
		double graduate = 0.0;
		double undergrad = 0.0;
		int expectedArg = 5;
		
		try {
			// Open the file that is the first 
			// command line parameter
			FileInputStream fstream = new FileInputStream("exams.dat");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			//Read File Line By Line
			while ((strLine = br.readLine()) != null)   {
			// Print the content on the console
				//System.out.println (strLine);
				//Try to put the args into the variables.
				if (strLine == expectedArg) {
				try {
					id = Double.parseDouble(args[0]);
					label = args[1];
					weight = Double.parseDouble(args[2]);
					graduate = Double.parseDouble(args[3]);
					undergrad = Double.parseDouble(args[4]);
				} catch (Exception e) {
					System.out.println("Error: ");
					e.printStackTrace();
					System.exit(1);
				} 
				}
			}
			//Close the input stream
			in.close();
	    }catch (Exception e){//Catch exception if any
	    	System.err.println("Error: " + e.getMessage());
	    }
	}
}

The "if (strLine == expectedArg)" part returns an error. I know it should be strLine.something but I'm not sure what. Any suggestions? Also, will this work in assigning the file arguments to variables?
 
Technology news on Phys.org
A couple of things to point out.

Consider using FileReader instead of FileInputStream. FileReader is designed to work with text-based files. Also, you wrap the FileInputStream with a DataInputStream followed by a BufferedReader. Is there any particular reason why you are doing this? I don't think it is really necessary. No big deal, just more work than you really need to do.

So you get your strLine from the BufferedReader via getLine. That contains your data, say:

Code:
123 Midterm .25 100

Now I'm assuming you want to parse the line and place the values in your id, label, weight, etc variables, right? The next thing you need to do is tokenize the String contained in strLine. This will turn it into an array of Strings. There's a convenience method on the String class called split. Check it out, it will tokenize the string for you.

http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

So basically you'd do something like:

Code:
String parts[] = strLine.split(regex);

Here's a hint. The regex will be the character that divides up the fields of the string.

Regarding your question about the if conditional, you are wanting to check to make sure you have the right number of columns, right? Tokenizing the string will help you accomplish that. Hint: the length of an array such as 'parts' can be had by accessing the 'length' property (e.g. parts.length).

Hope that helps. There are some other parts that need to be fixed, but hopefully this will get you on the right track.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top