Hi everyone,

I require some help for this project I am currently working on. Basically what I have to do is read from two text files, then calculate some numbers from both files (eg: add the numbers and average them) and after that, write the results to a another file. I have written a bit of code to read from the files but I am stuck at the moment.

import java.io.*;
import java.util.*;

public class Read
{
    public static void main(String [] args)
    {
        BufferedReader input;
        String line;
        String [] subject = new String[3];
        int i = 0;

        try
        {
            FileReader fr = new FileReader("Description.txt");
            input = new BufferedReader(fr);

            while ((line = input.readLine()) != null)
            {
                StringTokenizer tokenizer = new       StringTokenizer(line, ", \t");
                String token;

                while (tokenizer.hasMoreTokens())
                {
                    token = tokenizer.nextToken();
                    System.out.println(token);
    //              subject[i] = token;
    //              System.out.println(subject[i]);
    //              i++;
                }
            }

            input.close();
        }

        catch (IOException e)
        {
            System.err.println(e);
        }
    }
}

You see, I am trying to put each line of the text file into an array. Here is an example of the file:

Introduction to Software
Assignment, 100, 10
Tutorial, 100, 10

I know every line there are 3 strings. But what I am unsure of is how to put each line into a different array.

I hope someone can help. Thank you :)

Why do you need to store all the lines? Couldn't you just maintain the average of the numbers in a variable.

For example,

create a total & amount variable (for the average... average = total/amount)
double total =0;
double amount=0;

//for each line in the file
while ((line = input.readLine()) != null)
{

	//tokenize the line
	StringTokenizer tokenizer = new StringTokenizer(line, ",");

	//if there are 3 tokens in the line
	if( tokenizer.countTokens() == 3)
	{
		//get 1st token in line
		String str = tokenizer.nextToken();

		//get 2nd token in line
		int num1 = Integer.parseInt(tokenizer.nextToken().trim());

		//get 3rd token in line
		int num2 = Integer.parseInt(tokenizer.nextToken().trim());

		//add numbers to total
		total += num1 + num2;

		//increment amount
		amount++;
		
	}

}

//show average
System.out.println("Average is: " + total/amount);

You should give more information about your project so a better answer can be given. Hope the above helps.

For more help, www.NeedProgrammingHelp.com

NPH, thank you very much for the reply.

Sorry for not giving you more details. The question is something like this:

I am suppose to develop a simple reporting system to produce result files for students' performance in a certain subject. The information required to produce the results is stored on 2 files and the results is stored on another third file.

The first file is a subject description file, like I have shown earlier

Introduction to Software
Assignment, 100, 10
Attendance, 100, 10
Exam, 100, 70
Tutorial, 100, 10

(Item name, max score, scaled max score)

And the other is a assessment results file, like this

Introduction to Software
1234567, David, Assignment, 80, Attendance, 100, Exam, 75, Tutorial, 95

(Student ID, name, assessment item, score)

The final result file is suppose to be something like this

Introduction to Software
1234567, (final mark), (difference of final mark from average)

actualScore * scaledMaximumScore / maximumScore = formula to get final mark

I was planning to put the information into an array, but it seems to be quite complicated. There are a few problems that I have encountered. Such as not being able to choose which line to start reading the file from, or splitting each line into a different array.

Thanks again to anyone that helps :)

The hardest part is knowing how to store & structure the information once it is read.

Firstly, the program must be able to quickly answer the following question: Give me all info on a subject "Intro to Software". You should then be able to get the scale/non-scaled max scores for any assignment in the subject. You will need to do this when you read the students file and need to calculate the scores.

I recommend creating a class called Subject. Hashmaps can then be used to associate the name "Intro to Software" to an object of type Subject that holds all the info on Intro to Software. This lets you obtain all the info by just knowing the name.

This is not the entire solution but here is the idea. Instead of hard coding the data, you must read it from the file but it should help. Run it and read the comments.

import java.util.*;
//subject class
class Subject
{
	//name of subject
	private String name;
	
	//all the assignments in the subject
	private ArrayList assignments = new ArrayList();
	
	//constructor
	public Subject(String name)
	{
		this.name = name;
	}
	
	//add an assignment to subject
	public void addAssignment(Assignment assign)
	{
		assignments.add(assign);
	}
	
	//get an assignment from subject
	public Assignment getAssignment(String name)
	{
		for(int i =0; i < assignments.size(); i++)
		{
			Assignment assign = (Assignment)( assignments.get(i) );
			
			if(assign.getName().equals(name))
			{
				return assign;	
			}
		}
		
		throw new RuntimeException("Assignment " + name + " not found");
	}
	
}

//assignment
class Assignment
{
	//data
	private String name;
	private int maxScore;
	private int maxScaledScore;
	
	//constructor
	public Assignment(String name, int maxScore, int maxScaledScore)
	{
		this.name = name;
		this.maxScore = maxScore;
		this.maxScaledScore = maxScaledScore;
		
	}
	
	//get max score
	public int getMaxScore()
	{
		return maxScore;	
	}
	
	//get scaled max score
	public int getMaxScaledScore()
	{
		return maxScaledScore;	
	}
	
	//get name
	public String getName()
	{
		return name;	
	}
	
	//toString()
	public String toString()
	{
		return "The info is... Name: " + name + " Max Score: " + maxScore + " Scaled Max Score: " + maxScaledScore; 
	}
}

class Main
{
	public static void main(String[] args)
	{
		//create hashmap from name to Subject objects
		HashMap subjects = new HashMap();
		
		
		
		
		//create subject object
		Subject sub1 = new Subject("Intro to Something");
		
			//add assignments to object
			Assignment a11 = new Assignment("Assignment 1", 100, 15);
			sub1.addAssignment(a11);
			
			//add assignments to object
			Assignment a12 = new Assignment("Assignment 2", 100, 70);
			sub1.addAssignment(a12);
			
			//add assignments to object
			Assignment a13 = new Assignment("Assignment 3", 80, 20);
			sub1.addAssignment(a13);
			
		//add to hashmap
		subjects.put("Intro to Something", sub1);
		
		
		
		
		
		//create subject object
		Subject sub2 = new Subject("Intro to Typing");
		
			//add assignments to object
			Assignment a21 = new Assignment("Assignment 1", 67, 15);
			sub2.addAssignment(a21);
			
			//add assignments to object
			Assignment a22 = new Assignment("Assignment 2", 77, 15);
			sub2.addAssignment(a22);
			
			//add assignments to object
			Assignment a23 = new Assignment("Assignment 3", 72, 45);
			sub2.addAssignment(a23);
		
		//add to hashmap
		subjects.put("Intro to Typing", sub2);
		
		
		
		
		//get subject "Intro to Typing"
		Subject aSubjectWeWant = (Subject)( subjects.get("Intro to Typing"));
		
		//get assignment 2 from the subject object
		Assignment assignWeWant = (Assignment) ( aSubjectWeWant.getAssignment("Assignment 2") );
		
		//print out its max score
		System.out.println( "Max score of assignment 2 of subject 'Intro to Typing' is: " + assignWeWant.getMaxScore() );
			
	}
}

For more help, www.NeedProgrammingHelp.com

Wow... very nice code NPH.

Yea, like you said, I will have to change the main class code to implement the string tokenizer so that I can extract each line from the files and create an object out of it.

Can you explain what a hash map is? I don't think I have heard of it before.

The code will definitely help me on writing my code. Thank you so much :cheesy:

I have written some part of my main already but I have run into a problem. I get a null pointer exception from this code. Here is my main and my description class.

import java.io.*;
import java.util.*;

public class Assign1
{
	public static void main(String [] args)
	{
		BufferedReader input;
		String line;
		Description [] subject;
		int i = 0;
		int lineCount = 0;
		
		try
		{
			FileReader fr = new FileReader("Description.txt");
			input = new BufferedReader(fr);
			
			while ((line = input.readLine()) != null)
			{
				lineCount++;
			}
			
			System.out.println(lineCount);
			subject = new Description[lineCount - 1];

			while ((line = input.readLine()) != null)
			{
				StringTokenizer tokenizer = new StringTokenizer(line, ", \t");
				String token1, token2, token3;
		
				while (tokenizer.hasMoreTokens())
				{
					token1 = tokenizer.nextToken();
					token2 = tokenizer.nextToken();
					token3 = tokenizer.nextToken();
					subject[i] = new Description(token1, token2, token3);
					i++;
				}
			}
			
			input.close();
		}
		
		catch (IOException e)
		{
			System.err.println(e);
		}		
	}
}

class Description
{
	//variables
	private String name;
	private String maxScore;
	private String maxScaledScore;
	
	//constructor
	public Description(String name, String maxScore, String maxScaledScore)
	{
		this.name = name;
		this.maxScore = maxScore;
		this.maxScaledScore = maxScaledScore;
		
	}
	
	//get scaled max score
	public String getMaxScaledScore()
	{
		return maxScaledScore;	
	}

	//get max score
	public String getMaxScore()
	{
		return maxScore;	
	}
	
	//get name
	public String getName()
	{
		return name;	
	}
	
	//toString()
	public String toString()
	{
		return "The info is... Name: " + name + " Max Score: " + maxScore + " Scaled Max Score: " + maxScaledScore; 
	}
}

In my main class, I am trying to create an array of objects. So, each variable of subject contains the name, maxScore and maxScaledScore of the items in the subject. I hope anyone can help. Thank you

I am almost complete with my project. Thank you NPH for the help.

Moderators, may I delete my thread?

No, you can not delete a thread.
Let others learn something from it if they can (and go to the trouble to search for an answer before asking a question), that's what a public forum is for.

Alright.. thank you :-)

hmm... wat if there is an alphabet in the ID given? and i want to ignore that student marks and continue from it?

tried some ways, but it usually catch by the exception, and the program exit... :eek:

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.