logo CodeStepByStep logo

flipAndReverseLines

Language/Type: Java file input
Related Links:

Write a method named flipAndReverseLines that prompts the user to type a file name until the user types the name of a file that exists, then opens that file and reads its contents as a sequence of lines, and outputs to the console that file's contents with the following modifications made to them:

  • Successive pairs of lines (A, B) should be printed in reversed in order (B, A).
  • Lines should be printed with alternating capitalization. The first line printed should be entirely in uppercase; the second entirely in lowercase; the third in uppercase; the fourth in lowercase; and so on.
  • Every line's characters should be printed in reversed order. For example, the line "hi there" should be printed as "ereht ih". (Note that Java and our libraries do not include a built-in method to reverse a string.)

You should also return the total count of lines in the file as an integer.

For example, if the input file named carroll.txt contains the following nine lines of text (including the blank line in the middle):

TWAS brillig and the Slithy Toves
did GYRE and gimble in the Wabe.
All mimsey were the Borogroves,
and the mome RATHS outgrabe.

"Beware the Jabberwock, my Son,
the JAWS that bite, the claws that Catch,
Beware the JubJub bird and SHUN
The Frumious Bandersnatch."

Then the call of flipAndReverseLines(); should produce a console interaction in exactly the following format (user input shown like this):

Input file name? foo.txt
Unable to open that file.  Try again.
Input file name? file not found.doc
Unable to open that file.  Try again.
Input file name? carroll.txt

.EBAW EHT NI ELBMIG DNA ERYG DID
sevot yhtils eht dna gillirb sawt
.EBARGTUO SHTAR EMOM EHT DNA
,sevorgorob eht erew yesmim lla
,NOS YM ,KCOWREBBAJ EHT ERAWEB"

NUHS DNA DRIB BUJBUJ EHT ERAWEB
,hctac taht swalc eht ,etib taht swaj eht
".HCTANSREDNAB SUOIMURF EHT

The method would also return 9 since there are 9 lines in the file.

Notice the alternation between all-uppercase and all-lowercase. Also note that a line can be blank, as in the third pair. An input file can have an odd number of lines, as in the one above, in which case the last line is printed in its original position. You should not make any assumptions about how many lines are in the file.

Constraints: Your solution should read the file only once, not make multiple passes over the file data. Do not use any collections (ArrayList, TreeMap, array), etc. You may use strings and simple variables.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.