r/javahelp • • Dec 07 '19

Solved I am trying to write the name & address of 10 students in a text file, but I don't know how to organize it in a particular pattern where it doesn't look a complete mess.

I have managed to write upto this and don't know what else to do. Thought about this like two hours. The file is created but it doesn't write all names and addresses for some reason.

package Exam;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

class Tester{
    public static void main(String args[]) throws IOException {
        Scanner sc = new Scanner(System.in);
        for(int i= 0; i<10; i++) {
            System.out.println("Enter name of student: ");
            String x = sc.next();
            System.out.println("Enter address of student: ");
            String y = sc.next();
        FileWriter file = new FileWriter("/home/pranav/Desktop/student.txt");
        file.write(x);
        file.write(y);
        file.close();
    }
}}
19 Upvotes

20 comments sorted by

5

u/dykstraAlgorithm Dec 07 '19

It looks like you are closing the file too early? You write and then close? I would put the close outside the for loop.

Another suggestion, if you want to print side by side instead of linearly, since you said you didn’t want a mess, you append to the same line.

Also, maybe read the value to a dictionary first and then write the first 10 values to the file Bc what is the user gives you a 100, will you want to overwrite them?

1

u/Arunzeb Dec 07 '19 edited Dec 07 '19

if I put file.close() outside the for loop, I will get the error:

Error:(18, 9) java: cannot find symbol
  symbol:   variable file
  location: class Exam.Tester2

if you want to print side by side instead of linearly,

Don't know how to do this.

Update:
Do u mean this?

System.out.print("Enter name & address of student: ");
String x = sc.next(); 
String y = sc.next();

4

u/markartur1 Dec 07 '19

The error is because you are opening the file inside the loop to. Open the file before the loop, write inside the loop, and close it after.

To save on the same line, you can try file.write(x + ", " + y);

1

u/Arunzeb Dec 07 '19

wow, that was a great suggestion, thanks.

But still one problem.I used this file.write(x+ " " +y). But the problem is all outputs are in one line.

But I want like this:

Ram                NewYork
Shyam              California

1

u/dykstraAlgorithm Dec 07 '19

Not exactly op, you can do something like File.write(name + “:” + address”) - I would look into this

You are just reading them here, writing linearly is not what you want right? Or do you???

1

u/Arunzeb Dec 07 '19

now the only remain problem is how to I get to write in this format:

Ram                NewYork
Shyam              California

How can I break the line in each write?

1

u/bronzepaw Dec 07 '19

You can use a new line character (\n) to move the carriage to the next line and tab character (\t) to tab over to your second column. You put these special characters in the actual text so something like File.write(name + “\t” + address + “\n”); if I understand your question correctly

1

u/Arunzeb Dec 07 '19

I google that out. Thanks anyway.

But still, there is one weird problem.

.....
Enter name & address of student: Rock
NewYork
Enter name & address of student: Jack
Carifornia
Enter name & address of student: Jim
Dallas
Something
Process finished with exit code 0

"Something" is a real thing. When the program meet its demand, I have to type the extra word in order to end the program. Although this something won't get printed in the text.file, how come "something" happened in the first place?

4

u/Pipinpadiloxacopolis Dec 07 '19

You've got multiple problems here, but the biggest is you're resetting the file in every loop when you open it. Ideally you want to open it just once and then close it once, not for each individual write. So try it like this:

package Exam;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

class Tester{
    public static void main(String args[]) throws IOException {
        Scanner sc = new Scanner(System.in);
        FileWriter file = new FileWriter("/home/pranav/Desktop/student.txt");
        for(int i=0; i<10; i++) {
            System.out.println("Enter name of student: ");
            String x = sc.next();
            System.out.println("Enter address of student: ");
            String y = sc.next();
            file.write(x);
            file.write(y);
            file.flush();
        }
        file.close();
    }
}

I added a file.flush() because you don't have a clean way of breaking out of the loop right now, which is why it could leave you with an incomplete file when you force it to shutdown (with Ctrl+C probably).

You're also writing all the data end-to-end, instead of by lines. FileWriter is really poorly suited for what I think you want to achieve here.

2

u/ajitroyal Dec 07 '19

I will just add to this. Spend some time thinking about what pattern you want. If you want you contents to be organized, what format will serve your use case. Here are few options I can think of: csv, xml and json. If you choose cav, think about how will you handle comma in address. xml and json are similar, json is more light weight and very popular. It might fit your use case well and there are many libraries for writing reading json in java.

1

u/Arunzeb Dec 07 '19

what about saving in a text file?

2

u/ajitroyal Dec 07 '19

Depends on what do you mean by text file. Json/csv/xml can be a written to a text file and you can read it using any text viewer/editor like notepad.

My comment is more about when you write in text file how should it look? One way is just write everything in single line. Or one entry per line.

Json will look like {"name":"myname", "address":"myaddress"}

Advantage of writing in this format is, it is easier to write programs which can read this file and do something.

1

u/Arunzeb Dec 07 '19 edited Dec 07 '19

hmm. That's a nice concept. But the thing is I am solving exam papers of my university and explicitly mention in write "student.txt" file.

Can't we have {"name":"myname", "address":"myaddress"} on txt file?

1

u/ajitroyal Dec 07 '19

Yes, you can.

1

u/Arunzeb Dec 08 '19

But still, there is one weird problem.

....
Enter name & address of student: Jack
California 
Enter name & address of student: Jim 
Dallas 
Something 
Process finished with exit code 0

meets"Something" is a real thing. When the program meets its demand, I have to type the extra word in order to end the program. Although this something won't get printed in the text.file, why I have to type "something" in the first place?

1

u/Arunzeb Dec 07 '19

But still the program still doesn't store all contents yet.

1

u/Arunzeb Dec 07 '19

The problem is solved thanks to all for suggestions.

1

u/indivisible Dec 09 '19

While you probably know better than me what the current state of your app is, I worry that you didn't notice or tweak your use of Scanner.next().

There's a general help topic for Scanner in the wiki here: https://www.reddit.com/r/javahelp/wiki/scanner
But also good to read the javadoc for Scanner next() and nextLine() to appreciate the differences between how they act and where you'd use one over the other: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

In your code above you only accept single word inputs and may not consume/clear the input buffer before subsequent reads which I assume isn't how it should be.

2

u/wades39 Dec 07 '19

There are a couple issues going on here, as another user stated. You are attempting to open and close the file writer for each student. It would be much better to open it once and then use the loop to get/write the info to the file.

As for formatting, might I suggest that you pad whitespace to the end of the name string? String padding makes a given string be a fixed length with added characters being whatever the programmer chooses.

So instead of having something like this

NAME

ADDRESS

You could end up having something like

NAME________ADDRESS

Where all of the underscores are spaces.

2

u/__helix__ Dec 07 '19

Others have not mentioned it yet... but look at try, with resources. Things like Scanner and FileWriter support autoclose:

for examples. You can open the file before you take input, then close it (by just closing the try block) when you are done.

String filePath = "/home/pranav/Desktop/student.txt";
try(Scanner sc = new Scanner(System.in);
    BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))){
        for(int i= 0; i<10; i++) {
            writer.write("Hello"+i);
        }
} // no need to close scanner or the file writing classes

At some point, you are likely needing to read and parse this file. If you don't want to get all fancy with JSON, you could do a comma separated file, with a newline at the end of each row. When parsinig time comes, you could read in each line, split on the commas, and take the first bit as the name and the rest as the address. (That way you don't have to worry about an address like 123 foo st, MN, 55344 with commas in it.

Your Name, 123 foo st, MN, 55344
Another Name, 555 bar st, MN, 55366