-2

I need code to write a single line like Aidan Dowling to a text file. My code so far is:

package battleships.startmenu;
import java.util.Scanner;
public class Startmenu {

    public static void main(String[] args) {
        System.out.print("Hello! Please enter your first name: ");
        Scanner reader = new Scanner(System.in);
        String a;
        String b;
        a=reader.next();
        System.out.print("Enter your second name: ");
        b=reader.next();

        System.out.println("Hello " + a+ " " + b + "!");
        System.out.println("\tHello");
        String name;
        name = a + b;
    }
}

I want the variable name to print out to a document called name.txt

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3127013
  • 15
  • 1
  • 1
  • 4

2 Answers2

2

create a writer

PrintWriter writer = new PrintWriter("name.txt", "UTF-8");

write a line

writer.println(name);

close the writer

writer.close();
jmj
  • 237,923
  • 42
  • 401
  • 438
0

Writing name to name.txt:

Files.write(Paths.get("name.txt"), Arrays.asList(name), StandardCharsets.UTF_8);
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160