如何在一个文本文件中存储多个用户名

时间:2020-09-12 20:02:06

标签: java text

我的程序询问用户的姓名和年龄。用户名是其名称和年龄,并在其末尾添加一个随机字符。我想将该用户名存储到一个新的文本文件中,但是每当我运行代码时,它只会一次写入一个用户名,而不包括我之前添加的用户名。这是我的代码,请帮助我,我是新手。

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();
 





  }
  }

2 个答案:

答案 0 :(得分:0)

如果要向以前已经写入过文本的文件中写入文本,则需要使用FileWriter(File file,boolean append)构造函数:

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

除此之外,您的程序只要求输入一次,因此如果要添加多个用户名,则需要多次运行它。或者,您可以将完成的操作包装成一个循环,以要求多次输入。谈到循环,您真正拥有的一个循环没有真正目的,因为它执行的语句将运行一次,就像没有循环将它们包装起来一样。

答案 1 :(得分:0)

这是因为您每次都覆盖文件。

替换

<template>
  <div class="container">
    <div v-if="error.statusCode === 404">
      <h1>Page not found</h1>
      <p>{{ error.message }}</p>
    </div>
    <div v-else>
      <h1>An error occurred</h1>
    </div>
    <n-link to="/">Home page</n-link>
  </div>
</template>

<script>
export default {
  props: ['error'],
  layout: 'default' // If you prefers you can set a custom layout for the error page
}
</script>

使用

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