In: Computer Science
Java Code using Queue
Write a program that opens a text file and reads its contents into a queue of characters, it should read character by character (including space/line change) and enqueue characters into a queue one by one. Dequeue characters, change their cases (upper case to lower case, lower case to upper case) and save them into a new text file (all the chars are in the same order as the original file, but with different upper/lower case)
use linked list class, use nextLine() to read one line into a String, then use String's charAt(i) in a for loop to get characters out one by one, add one extra line change char at the end as '\n'
Ex input file:
The Brown Fox
Jumped
EX output file:
tHE bROWN fOX
jUMPED
Raw_code:
import java.util.*; // importing LinkedList and Scanner
class
import java.io.*; // importing FileWriter and PrintWriter class
public class main{
// main function
public static void main(String[] args)
throws Exception{
// crating file object on input text file and Scanner object of
File object
File filein = new File("input.txt");
Scanner input = new Scanner(filein);
// creating FileWriter object on output text file and PrintWriter
object on FileWriter object
FileWriter fileout = new FileWriter("output.txt");
PrintWriter output = new PrintWriter(fileout);
// creating LinkedList of Character
LinkedList<Character> queue = new
LinkedList<Character>();
// temporary String variable for storing each line read from input
file
String temp_str;
while(input.hasNext()){
// reading line by line from input file and storing in
temp_str
temp_str = input.nextLine();
// iterating over the temp_str
for(int ind = 0; ind<temp_str.length(); ind++)
// adding each character in string to queue
queue.add(temp_str.charAt(ind));
// adding new character to queue for each new line read from input
file
queue.add('\n');
}
// temporary Character variable for storing each Character in
queue
Character temp_char;
// iterating over each Character in queue
for(int ind = 0; ind < queue.size(); ind++){
// getting the Character and storing in temp_char
temp_char = queue.get(ind);
// checking whether Character is alphabet or not
if(Character.isAlphabetic(temp_char))
// if character is in lower case
if(Character.isLowerCase(temp_char))
// replacing the lower case character by converting upper
case
queue.set(ind, Character.toUpperCase(temp_char));
// if character is in upper case
else if (Character.isUpperCase(temp_char))
// replacing the upper case character by converting lower
case
queue.set(ind, Character.toLowerCase(temp_char));
}
// iterating thorugh each Character in queue
for(var character: queue)
// writing each Character to output file
output.write(character);
// for debugging
System.out.println("Written to output file");
// closing both input and output file streams
output.close();
input.close();
}
}