Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving multiple user inputs to a text file

Firstly I must apologize if this has already been explained... While I have done searches to find an answer to my problem, I am still very new when it comes to Java so I couldn't really understand. (I've only been learning Java for a couple of days.)

My friend, who is trying to teach me Java sets me assignments that I have to complete and I'm supposed to learn what I need to do to complete these assignments myself. Recently he gave me the challenge of creating a program that asks the user for their name, age and a username. This program then needs to output these in a sentence. That part is easy. What I'm having difficulty with is the next part where I have to make the program save these to a file, along with any future inputs from a user.

Here's what I have:

import java.util.Scanner;

public class easy1 
{

@SuppressWarnings("resource")
public static void main(String[] args)
{
    System.out.println("Enter your name, age and username: ");
    Scanner sc = new Scanner(System.in);

    String name = sc.next(), age = sc.next(), user = sc.next();

    System.out.println("Your name is " + name + ", you are " + age + " years old, and your username is " + user + ".");
}
}

I'm not really looking for anybody to tell me what to do, what I would appreciate is just a little guidance or a clue as to what I should be doing. If you do give me an answer then an explanation of how it works would be nice.

Thank you.

like image 966
family2dyl Avatar asked Dec 25 '22 18:12

family2dyl


1 Answers

To save to file you need to create a File object.

File file = new File("someFile.txt");   -- takes file name as argument.  

Then you need a way to print to the file. You can use PrintWriter

PrintWriter writer = new PrintWriter(file);  -- takes file as argument.

To write to the file, just use the PrintWriter write() method

writer.write(name);

If you're only in your second day of learning, tell your friend it's too early to be learning about I/O (input/output). You should be learning about loops, arrays, methods, operators, if/else if statements, Strings, etc. All the basics. Once you've finished the basics, you're ready to get into Object Oriented Programming (OOP). That's where the real magic happens. So take time to learn the basics, so you'll be ready for the deeper stuff.

Pick up a comprehensive book. I'd recommend a textbook Introduction to Java Programming by Daniel liang

like image 148
Paul Samsotha Avatar answered Dec 28 '22 06:12

Paul Samsotha