*****The following JAVA code does the following: (NOT WHAT NEEDS TO BE ANSWERED)
ID: 653755 • Letter: #
Question
*****The following JAVA code does the following: (NOT WHAT NEEDS TO BE ANSWERED)
Create a file containing 100 randomly generated upper case characters.
Display the contents of the file in 10 rows of 10 characters.
Open the file for random access.
Prompt the user for a position to modify in the displayed characters, and the character to write to that position.
Display the modified contents.
Sample run of original program
*** What I need is for this code to be expanded to replace every occurence of a single letter, for example E. Every E will be replaced with what the user specifies. The location of every e will also be outputted. So the two things I need expanded are
1) Change every occurance of a single letter (example E)
2) output the location in a similar manner as original program asked user to specify which letter is to be changed (example E's at 2,3,4, and 5)
JAVA CODE************
Explanation / Answer
import java.io.*;
import java.util.Scanner;
class fileTest3
{
public static void main(String[] args)throws IOException
{
char randChar;
if(args.length != 1)
{
System.out.println("No path\filename entered");
System.exit(1);
}
String theFile = args[0];
try( DataOutputStream output = new DataOutputStream(new FileOutputStream(theFile));
DataInputStream input = new DataInputStream(new FileInputStream(theFile)); )
{
//begin try with resources // write 100 random upper case characters to file
for(int i = 0; i < 100; i++)
{
randChar = (char)('A' + Math.random() * ('Z' - 'A' + 1));
output.writeChar(randChar);
} // display file contents
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
System.out.print(input.readChar() + " ");
}
System.out.println();
}
}//end try with resources
//Random access -----------------------------------
Scanner input = new Scanner(System.in);
RandomAccessFile raf = new RandomAccessFile(theFile, "rw");
System.out.println("Current length of the file is: " +raf.length());
System.out.print("Replace character number: ");
while(!raf.EOF)
{
int position = input.nextInt();
System.out.print("with the character: ");
String theChar = input.next();
raf.seek((position-1)*2);
raf.writeChars(theChar);
}
raf.close();
try( DataInputStream input2 = new DataInputStream(new FileInputStream(theFile));
)
{
//begin try with resources
// display file contents
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
System.out.print(input2.readChar() + " ");
}
System.out.println();
}
}
//end try with resources
}
// end main
}//end class
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.