So if I've got 4 lines in the txt file, how can I take all the even numbered lines (2 & 4) and switch there places with the odd numbered lines? For Example: This is the starting text.
Twas brillig and the slithy toves
did gyre and gimble in the wabe.
All mimsey were the borogroves,
and the mome raths outgrabe.
This is how I want to flip it:
did gyre and gimble in the wabe.
Twas brillig and the slithy toves
and the mome raths outgrabe.
All mimsey were the borogroves,
This is what I've got so far:
public static void flipLines(Scanner console) {
String text = console.nextLine();
while (console.hasNextLine()) {
}
}
Sorry it's not very much, but I'm not sure how to go about it. Is there a way to create an index for each line so I can call them in order like 2, 1, 4, 3 or...?
CodePudding user response:
add them to a String
with the order you want, put 2nd line first then first line second :
public static void flipLines(Scanner console) {
String text = "";
while (console.hasNextLine()) {
String first = console.nextLine(); // getting first line
if (!console.hasNextLine()) { // this is incase we have odd number of lines, we don't want to have an error.
text = first;
break;
}
String second = console.nextLine();
text = second "\n" first;
if (console.hasNextLine()) { // this will make sure there are no extra empty lines if this was the last line.
text = "\n";
}
}
System.out.println(text);
}
but a better way to do it, is to use a StringBuilder
, its better to be used in loops that will be adding and changing strings alot, helps with performance and memory. Strings everytime you add something to it the computer creates new String
in memory for us, StringBuilder
just keep the same String
but mutate it.
public static void flipLines(Scanner console) {
StringBuilder text = new StringBuilder();
while (console.hasNextLine()) {
String first = console.nextLine();
if (!console.hasNextLine()) {
text.append(first);
break;
}
String second = console.nextLine();
text.append(second).append("\n").append(first);
if (console.hasNextLine()) {
text.append("\n");
}
}
System.out.println(text.toString());
}