This is a beta version of Practice-It. Give us feedback

logo Practice-It logo

switchData

Language/Type: Java file processing Scanner
Author: Stuart Reges (on 2020/10/06)

Write a static method called switchData that takes as a parameter a Scanner containing an input file of labeled data and that prints the same information with successive pairs of numbers on each line switched in order. Each line of the input file will consist of a label followed by a sequence of integers. For example, if a variable called input refers to the following file:

            Karen 1 2 3 4 5 6
            Sam 38 14 79 4 -3
            42 2 4 6 8 12
            extras
            anon 15
        

then the call switchData(input); should produce the following output:

            Karen 2 1 4 3 6 5
            Sam 14 38 4 79 -3
            42 4 2 8 6 12
            extras
            anon 15
        

The first line of the file has the label "Karen" followed by 6 integers. Notice that the first pair of integers (1, 2) has been switched (2, 1), and the second pair of integers (3, 4) has been switched (4, 3), and so on. This first example involved sequential integers to make the switching more obvious, but this won't always be the case. You also shouldn't assume that you have an even number of integers. If there is an odd number of integers, as in the second line of input, then the final value should not be moved (the -3 appears at the end in both input and output).

There will always be a one-word label (possibly a number as in the example of "42"), but the list of integers might be empty, in which case the method simply prints the label on a line by itself (as in the example of "extras"). You may assume that the input is legal (a sequence of lines each with a one-word label followed by 0 or more integer values). You may not construct any extra data structures to solve this problem other than Scanner objects.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.