0

My program asks the user for their name and age. The username is their name and age plus a random character at the end of it. I want to store that username into a new text file but whenever I run the code it only writes one username at a time it doesn't include the one that I added before. Here is my code Please help me I am new.

import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Userfile {

private static String name;
private static Scanner scanage;
private static Scanner scan;

public static void main(String[] args) throws IOException {
    Random r = new Random();
    int age;
    String username;
    char randomc = 2;
System.out.println("Please enter your name");

 scan = new Scanner(System.in);
 name = scan.nextLine();
 
 System.out.println("Please enter your age");
 scanage = new Scanner(System.in);
 age = scanage.nextInt();
 username = name.toLowerCase()+age;
 


     String alphabet = "xy!&69£zHDErnABCabcFfGghIiJjKkLlMmNPp";
     for (int i = 0; i < 1; i++) {
     randomc = alphabet.charAt(r.nextInt(alphabet.length()));
     String userId = username + randomc;
     System.out.println("Your Username is " +userId);
    }
       


  FileWriter userid = new FileWriter("file path");

  String userId = username + randomc;
  userid.write("\n" + "Username: " + userId);
  userid.close();
 





  }
  }
  • Hint: always read the javadoc for new classes you use. FileWriter has another ctor that allows to tell it to APPEND in case the file exists already. – GhostCat Sep 12 '20 at 20:11

2 Answers2

0

If you want to write text to a file to which you've already written text before, you need to use the FileWriter(File file,boolean append) constructor:

FileWriter userid = new FileWriter("file path", true); //assuming "file path" is the actual path to the file

Besides that, your program only asks for input once, so you'll need to run it multiple times if you want to add multiple usernames. Or you could wrap what you've done in a loop to ask for input multiple times. And speaking of loops, the one loop you do have serves no real purpose as the statements it executes will run once, just like they would without a loop wrapping them.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24
0

It's because you are overriding the file everytime.

Replace

FileWriter userid = new FileWriter("file path");

with

FileWriter userid = new FileWriter("file path", true);
Spectric
  • 30,714
  • 6
  • 20
  • 43
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37