I have a text file that looks like this:
Hello
a/m
The letter "a" is a command that is supposed to append the letter "m" that is followed by the slash to the end of the word "Hello"
How would I write a Java program to read and scan the file, and when the letter "a" is found, it appends "m" to the phrase "Hello"?
The output should print "Hellom"
import java.io.*;
import java.util.Scanner;
import java.util.*;
public class append {
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream f=new FileInputStream("G:/Java worksplace/file/src/file/input.TXT");
Scanner sc=new Scanner(f); //file to be scanned
String s1=""; // initialize the output the string with ""
while(sc.hasNextLine()) // Checks if the file has another line to read
{
String s= sc.nextLine();
if(s.contains("Hello"))
s1=s; // initializes the output string to Hello if it is the first line which contains hello.
if(s.startsWith("a"))
s1=s1+s.charAt(2); // when the letter "a" is found, it appends "m" to the phrase "Hello" i.e our output string s1
}
System.out.println(s1);
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is the screenshot of the program :
This is the screenshot of the Output :
Get Answers For Free
Most questions answered within 1 hours.