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
5 Réponses
+ 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
0
My answer Working //CODING BY PYSCODES import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] inputs = new String[3]; // Read three inputs for (int i = 0; i < 3; i++) { inputs[i] = scanner.nextLine(); } // Print the inputs for (String input : inputs) { System.out.println(input); } scanner.close(); } }
27th Jun 2024, 1:17 AM
PYSCODES
PYSCODES - avatar