Creating and writing files in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Creating and writing files in java

I have to output three task, but I don't how. Can someone tell me? (pls, write down the missing code) import java.io.File; import java.util.Scanner; import java.util.Formatter; public class Main { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); try { Formatter f = new Formatter("tasks.txt"); int count = 0; while(count < 3) { //your code goes here count++; } f.close(); } catch (Exception e) { System.out.println("Error"); } readFile(); } public static void readFile() { try { File x = new File("tasks.txt"); Scanner sc = new Scanner(x); while(sc.hasNext()) { System.out.println(sc.next()); } sc.close(); } catch (Exception e) { System.out.println("Error"); } } }

25th Mar 2021, 10:44 PM
Zotta
Zotta - avatar
4 Answers
+ 1
26th Mar 2021, 2:47 AM
zemiak
+ 1
import java.io.File; import java.util.Scanner; import java.util.Formatter; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); try { Formatter f = new Formatter("tasks.txt"); int count = 0; while (count < 3) { String task = input.nextLine(); f.format("%s%n", task); count++; } f.close(); File x = new File("tasks.txt"); Scanner sc = new Scanner(x); while (sc.hasNext()) { System.out.println(sc.nextLine()); } sc.close(); } catch (Exception e) { System.out.println("Error"); } } }
27th May 2023, 6:31 AM
Luis Suarez
0
did you find the answer?
15th Jun 2021, 6:52 PM
Vitali
Vitali - avatar
0
The Scanner input has to be passed as a string in the while loop. So: //add to while loop String in = input.next(); f.format(in + " \n");
7th Sep 2021, 12:54 AM
Taryn Nicole Jones
Taryn Nicole Jones - avatar