If I have multiple text files I want information from, how do I go about retriev
ID: 3908121 • Letter: I
Question
If I have multiple text files I want information from, how do I go about retrieving the information based on user choice? For instance, if I ask user to enter a number (1, 2, 3, etc.) and the number they decide will go with one of the text files. Do I store their choice in a variable and use if-else if? I want a scanner to scan through the file, not print it to console, and retreive parts of the text file where I have <text> in carrot brackets for the user to fill in. How do i only print that to the user and not the whole text?
Explanation / Answer
/*Opens a file , whereever <text> is there , takes user input and fills that data
in the file. Creates an updated file */
import java.io.*;
import java.util.*;
public class Demo197{
public static void main(String[] args){
try {
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("1.open a file");
System.out.println("2.Quit");
System.out.println("Enter choice:");
int n = Integer.parseInt(sc.nextLine());
if (n == 2)
break;
if (n == 1){
System.out.println("Enter filename:");
String nm = sc.nextLine();
FileInputStream fin = new FileInputStream(nm);
FileOutputStream fout = new FileOutputStream(nm+"_out.txt");
PrintWriter pw = new PrintWriter(fout);
Scanner fc = new Scanner(fin);
while (fc.hasNextLine()){
String line = fc.nextLine();
if (line.contains("<text>")){
System.out.println("Enter data:");
String line1 = sc.nextLine();
pw.println(line1);
}
else {
pw.println(line);
}
}
pw.close();
fout.close();
fin.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.