Java: Fix Error & Read File Args to Variables

  • Java
  • Thread starter Sam032789
  • Start date
  • Tags
    Java
In summary, the program reads in a file containing test data. It parses the data and assigns the values to variables. If there is an error, it prints out what the error was.
  • #1
Sam032789
11
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
  • #2
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.
 

1. How do I fix errors in my Java code?

To fix errors in Java, you need to identify the specific error and then troubleshoot the code to find the source of the error. Common errors in Java include syntax errors, logic errors, and runtime errors. You can use debugging tools and review your code line by line to find and fix errors.

2. How can I read file arguments and store them in variables in Java?

To read file arguments and store them in variables in Java, you can use the FileReader and BufferedReader classes. First, create a new instance of FileReader with the path to your file as the argument. Then, wrap the FileReader in a BufferedReader to read the file line by line. Finally, use split() on each line to separate the arguments into variables.

3. What is the purpose of using variables in Java?

Variables in Java are used to store data and values that can be manipulated and used throughout the code. They allow for dynamic and flexible programming, as the values can be changed or updated as needed. Variables also make code more readable and organized, as they can be given meaningful names that describe their purpose.

4. How do I declare and initialize variables in Java?

To declare and initialize variables in Java, you first need to choose a data type for the variable (such as int or String). Then, use the syntax dataType variableName = value; to declare and assign a value to the variable. You can also declare multiple variables of the same data type on one line by separating them with a comma.

5. Can I use variables in Java to perform mathematical operations?

Yes, variables in Java can be used to perform mathematical operations. You can declare variables to hold numeric values and then use operators like +, -, *, and / to perform addition, subtraction, multiplication, and division. You can also use variables in more complex mathematical expressions and equations.

Similar threads

  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
3
Views
777
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
1
Views
7K
  • Programming and Computer Science
Replies
5
Views
4K
Back
Top