gpt4 book ai didi

java - 如何将用户的输入保存到单独的文本文件中

转载 作者:行者123 更新时间:2023-12-02 02:52:14 25 4
gpt4 key购买 nike

首先,我必须道歉,因为有很多这样的问题,但我不太明白。我正在学习 Java 教程,但我被困在这里了。

如何将用户的输入存储到文本文件中?

这是我的代码。

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;

public class UserInput {

public static void main(String[] args) {

ArrayList<String> fullName = new ArrayList<String>();
ArrayList<String> userId = new ArrayList<String>();
ArrayList<String> qA = new ArrayList<String>();

Scanner sc = new Scanner(System.in);

while (true) {

System.out.println("Please enter your Full Name: ");
fullName.add(sc.nextLine());

System.out.println("Please enter your ID: ");
userId.add(sc.nextLine());

System.out.println("What is your race/ethinicity? A. Hispanic/Latino, B. Asian, C. Caucasian, D. African American: ");
qA.add(sc.nextLine());

System.out.println("What is your preferred language? A. Spanish, B. English, C. Portugues, D. French: ");
qA.add(sc.nextLine());

System.out.println("What is your political affiliation? A. Republican, B. Democrat, C. Green, D. None: ");
qA.add(sc.nextLine());

System.out.println("What is your religious practice? A. Christian, B. Islam, C. Judaism, D. Hinduism: ");
qA.add(sc.nextLine());

System.out.println("What is your sexual orientation? A. Homosexual, B. Heterosexual, C. Bisexual, D. Asexual: ");
qA.add(sc.nextLine());

System.out.println("What is your favorite ice cream? A. Vanilla, B. Chocolate, C. Banana, D. Gum: ");
qA.add(sc.nextLine());

System.out.println("What is your favorite activity? A. Running, B. Walking, C. Sleeping, D. Eating: ");
qA.add(sc.nextLine());

System.out.println("What is your favorite color? A. Burgundy, B. Black, C. Gold, D. Blue: ");
qA.add(sc.nextLine());

System.out.println("What is your favorite clothing item? A. Shoes, B. Hats, C. Shirts, D. Rings: ");
qA.add(sc.nextLine());

System.out.println("What is your favorite pet? A. Dog, B. Cat, C. Tiger, D. Turtle: ");
qA.add(sc.nextLine());

Random random = new Random();

for (int i =0; i < 1; i++) {

int answerScore = random.nextInt(10) + 1;
System.out.println("Test Score " + answerScore + "/10");

}

break;

}
}

}

我想知道如何将用户的姓名、ID 和答案存储到单独的 .txt 文件中。

提前致谢!

最佳答案

 public void saveData(ArrayList<String>fullName){ 
try {
File newTextFile = new File("D:/textfile.txt");//path of the file
FileWriter fw = new FileWriter(newTextFile);
for(String str: fullName) {
fw.write(str);
}
fw.close();

} catch (IOException io) {
io.printStackTrace();
}

关于java - 如何将用户的输入保存到单独的文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43638219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com