This site requires JavaScript, please enable it in your browser!
Greenfoot back
Omniscience
Omniscience wrote ...

2012/3/24

Reading and Writing to File

1
2
Omniscience Omniscience

2012/3/24

#
I have a simple Comma Separated Value file that stores 3 lines. Each line in the CSV (from left to right) abides by the following format: Question,Answer A,Answer B,Answer C,Answer D,Correct Answer,_____,______ Where the Question is a simple Maths Question (i.e. how many sides does a rhombus have?), the four possible answers (from A-D) are just numeric values (such as is the way the questions are designed), the Correct Answer is the letter representing the correct answer to the question, i.e. D. I need to be able to read each of the 3 lines of the CSV into separate one dimensional arrays. This should be done at the start of run time. You will notice that there are two spaces after "Correct Answer"; the first (from left to right) is where I need the game player's answer to be written to the file. Answers submitted will range from A-D, in all situations. The next empty space is where the game writes whether the player got that question correct. This will work by comparing the character (from A-D) submitted by the player with the Correct Answer (from A-D), stored within the array. The space should then have CORRECT or INCORRECT written into it as a result. This is a BIG ask, and I would much appreciate ANY feedback on how I should go about doing this, seeing as I have never done this kind of thing before!
Busch2207 Busch2207

2012/3/24

#
Where exactly do you have problems? Have you problems with reading the file, or with the evaluation of the String?
Omniscience Omniscience

2012/3/24

#
I have little idea as to how to read OR write files. All I ask is a programmatic demonstration on how this could be done for my particular situation (the OP). Thanks Busch2207!
davmac davmac

2012/3/24

#
and I would much appreciate ANY feedback on how I should go about doing this, seeing as I have never done this kind of thing before!
This question looks a lot like a homework problem. While asking for general guidance is fine, asking for help with such specific problems like this - although you haven't specifically asked someone to write the code for you - basically looks like you are trying to cheat. Let's assume though that that is not what you were intending; I'll point out two ways in which this question is bad: 1. Too much detail at once. You're not asking for help with a specific part, you're asking for help with the whole thing. It's not clear which parts you can do and which you can't. 2. You don't appear to have even tried to solve this problem yourself. You haven't posted any code, and neither have you posted any of your thoughts about how you might go about solving the problem. 3. You haven't put in any effort but you are asking for help. Because the question is general, I'll give a general answer. It's the same answer as for any 'how do I do '. It is: 1. Break the solution down into a sequence of steps, i.e. an algorithm, and then 2. Write the algorithm in Java code. for part (1) a good way to get started is to think about what classes and what methods you might need.
davmac davmac

2012/3/24

#
(Ok, I can't count. That's 3 ways the question was bad). Looks like others posted while I was typing, and you've now narrowed the problem down. That's good, but I hope you take my point.
Omniscience Omniscience

2012/3/24

#
@davmac I've taken on board what you've said. Here's my response.
This question looks a lot like a homework problem.
First off, I am a second year A Level student. I don't get homework, much. This happens to be my coursework.
While asking for general guidance is fine, asking for help with such specific problems like this - although you haven't specifically asked someone to write the code for you - basically looks like you are trying to cheat.
...... the very fact that I haven't asked for code goes to show that I am not "cheating"? As you are probably aware, this is my first time doing this, so general guidance was all that I needed.
Too much detail at once. You're not asking for help with a specific part, you're asking for help with the whole thing. It's not clear which parts you can do and which you can't.
I'm sorry if I haven't been clear. Here is the immediate part I need help with:
I need to be able to read each of the 3 lines of the CSV into separate one dimensional arrays. This should be done at the start of run time.
You haven't put in any effort but you are asking for help.
What I do not understand is that this site is where people come to when they have done their research, but they haven't been able to formulate a programmatic answer. This is the exact reason why I have not asked for code, but rather asked for guidance to get started. I am aware that just getting the coded solution is futile for educational growth. Do you see where I'm coming from?
matt.milan matt.milan

2012/3/24

#
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html http://docs.oracle.com/javase/6/docs/api/java/io/FileReader.html there might be others, but i think a combination of these might work
davmac davmac

2012/3/24

#
First off, I am a second year A Level student. I don't get homework, much. This happens to be my coursework.
Homework or coursework, my point still applies.
...... the very fact that I haven't asked for code goes to show that I am not "cheating"?
Yes, that's why I said "although you didn't ask for code"; you've just misinterpreted me here. If you had asked for code, it would have looked a lot more like cheating. My point was, although you didn't specifically ask for code, it still looks like that's what you want - particularly because your question was so vague.
I'm sorry if I haven't been clear. Here is the immediate part I need help with: I need to be able to read each of the 3 lines of the CSV into separate one dimensional arrays. This should be done at the start of run time.
Ok, but you could get more specific still. Is it that you don't know how to read files at all, or that you're not familiar with the CSV format, or are you able to read a line but don't know how to break it up into separate values?
What I do not understand is that this site is where people come to when they have done their research, but they haven't been able to formulate a programmatic answer. This is the exact reason why I have not asked for code, but rather asked for guidance to get started. I am aware that just getting the coded solution is futile for educational growth. Do you see where I'm coming from?
But there's absolutely no evidence that you have in fact done your research - that's what I was getting at. The problem is not that you are asking a question (and neither am I actually accusing you of cheating), the problem is the way you asked it. It's good that you didn't ask for code, however, and it's good that you understand that having a solution spoon-fed to you will not help you in the long term. I wish everyone understood that. Anyway, let me apologize. I just want to help you to formulate your posts in a way that will allow people to help you in a meaningful way. I'm sorry that it came across as if I was attacking you. I really am trying to help.
Duta Duta

2012/3/24

#
This should lead you in the right direction:
import java.io.*;
public class Example
{
    BufferedReader in;
    PrintWriter out;

    public Example()
    {
        try {
            startUp();
        } catch(Exception e) {
            System.err.println("An error occured");
            e.printStackTrace();
        }
    }
    
    private void startUp() throws Exception
    {
        //Creating your reader and writer
        String file = "YourFile.txt";
        in = new BufferedReader(
            new InputStreamReader(
                getClass().getClassLoader().getResourceAsStream(file)));
        out = new PrintWriter(file);
        
        /*
         * How to read lines
         * This loops through the file, reading one line at a time
         * until it reaches the end. With each line it just prints
         * it out, however for you you'd manipulate it and store
         * it in your arrays.
         */
        String line;
        while((line = in.readLine()) != null)
            System.out.println(line);
        
        /*
         * How to write lines
         * This writes:
         * ------------
         * Hi this is
         * a demonstration
         * on writing to
         * files!
         * ------------
         * to the file.
         */
        String[] lines = {
            "Hi this is",
            "a demonstration",
            "on writing to",
            "files!"};
        for(String lineToWrite : lines)
            out.println(lineToWrite);
    }
}
I don't want to give you it exactly as you need it, as that's (in my experience) one of the points of programming: to get methods of doing things and work out how you can apply them in your situation. If you really get stuck, post again. Oh and there might be some syntax errors in the above code (I doubt it though) because I typed it straight into the reply box without doing a "will-it-compile" check
matt.milan matt.milan

2012/3/25

#
let's assume the variable is private int answer; public void transferFilesToAnswersArray() { int i = o; while(readFile != noMoreText()) { answer = readFile(fileToRead, until charFound == ",") i++; } does this make sense? the check would be if (answer == correctAnswer) points++; else points--;
Duta Duta

2012/3/25

#
matt.milan wrote...
let's assume the variable is private int answer; public void transferFilesToAnswersArray() { int i = o; while(readFile != noMoreText()) { answer = readFile(fileToRead, until charFound == ",") i++; } does this make sense? the check would be if (answer == correctAnswer) points++; else points--;
Some of your code confuses me - for instance, what is the variable readFile (in the while loop). Another thing is that if you're making an int variable and incrementing it each time surely this would be better: for(int i = 0; readFile != noMoreText(); i++). There were some other parts which confused me however I'll just post what I was intending to post now: Here's an alternate way to matt.milan's, of reading the file and then sorting them into their respective arrays: (Bear in mind THIS MAY NOT WORK, as once again I've just written it on-the-fly, so haven't checked it.
/*
 * I assume you've created your BufferedReader and called it "in"
 * This also instead of just reading 3 questions, it reads however
 * many questions there are in the file.
 */
import java.util.List;
import java.util.ArrayList;

List<String>
	question = new ArrayList<String>(),
	answer_a = new ArrayList<String>(),
	answer_b = new ArrayList<String>(),
	answer_c = new ArrayList<String>(),
	answer_d = new ArrayList<String>(),
	answer_correct = new ArrayList<String>();
String line;
while((line = in.readLine()) != null)
{ try {
	question.add(line.substring(0, line.indexOf(',')));
	line = line.substring(line.indexOf(',') + 1, line.length());
	answer_a.add(line.substring(0, line.indexOf(',')));
	line = line.substring(line.indexOf(',') + 1, line.length());
	answer_b.add(line.substring(0, line.indexOf(',')));
	line = line.substring(line.indexOf(',') + 1, line.length());
	answer_c.add(line.substring(0, line.indexOf(',')));
	line = line.substring(line.indexOf(',') + 1, line.length());
	answer_d.add(line.substring(0, line.indexOf(',')));
	line = line.substring(line.indexOf(',') + 1, line.length());
	answer_correct.add(line.substring(0, line.indexOf(',')));
} catch(Exception e) {}}
//If you really need it in arrays:
String[]
	q = question.toArray(),
	a = answer_a.toArray(),
	//etc
matt.milan matt.milan

2012/3/25

#
yeah my code confused me too... it was suposed to be psuedocode but it wound up being incomplete "actual" code. i like your use of ArrayList though, that makes sense and it's quite flexible
danpost danpost

2012/3/25

#
This should do the same, and also is not tested or compiled:
int maxQuestions = 3;
int questionCount;
String[][] data = new String[maxQuestions][8];

for (int count = 0; count < maxQuestions; count++)
{
    line = in.readLine();
    if (line == null) break;
    for (int field = 0; field < 7; field++)
    {
        data[count][field] = line.substring(0, line.indexOf(','));
        line = line.substring(line.indexOf(',') + 1);
    }
    data[count][field] = line;
}
questionCount = count;
EDITED: If need be you can qualify the parsing of the last two fields by adding the following before it:
if (line.indexOf(',') < 0) break;
danpost danpost

2012/3/25

#
I just noticed that there is probably a happy medium between the two sets of code provided (using 'while' and 'for') Also, before line 5 add 'int count;' and remove 'int' from line 5.
Duta Duta

2012/3/25

#
@danpost
Omniscience wrote...
into separate one dimensional arrays.
There are more replies on the next page.
1
2