How can I switch the position of a line with the line after it in a text file using a Scanner?

Micah Cave

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...?

Emad Ali

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());
}

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How can I use each line of a file as an input switch in bash?

How do I replace line-by-line text of a file in C?

How do I loop though a text file, line by line, and append each line to an array?

How can I insert a new line into a text file into every other 2 lines?

How to read text file line by line?

how to read text file line to line in python

How could I get the text after the line break? Javascript

how can i view the first line of every file in my directory using python

How do I separate a each text file line into a separate lists?

Regex: How to insert text before the first line and after the last line of file

How I can prevent line break after codeigniter error message?

How can I process data after a specific line in python 2.6?

How can i go to next line inside the th:text in Thymleaf?

Gratient Module how can i print text in the same line

How can I align a Material icon & header text on the same line?

How can I add a line between output text?

How can I create a new "file type" in the command line?

How can i cast the .nth() line in a file as an integer?

How can I use File.AppendAllText and add to it a new line?

How can I skip the first and the last line of a file in PHP

How do i make python choose randomly one line after the first line of a file?

How do i make python choose randomly one line after the first line of a file?

JavaFX - On Windows 10 can I set an environment variable instead of using command line classpath switch?

how to reading .txt file , and adding space after specific position/index , for each line in python

How do I replace a line in a file using PowerShell?

How can I add line numbers to a textarea using an ordered list?

How can I find a specific position of a character from a line of code I'm evaluating

delete last line in text file using batch

While using ddd(display debugger), how can I go back to where execution stopped in the source line after some navigation?

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo