S
S
Sawayadi2020-11-27 13:46:54
Java
Sawayadi, 2020-11-27 13:46:54

How to rearrange the last word with the first word in the first line, the last word in the second line with the second one, and so on?

You need to enter several lines and make this method: rearrange the last word in the first line with the first word, in the second line the last word on the second, etc.
I tried to do it myself, but it does not work out to enter several lines.

package com.company;
 
import java.util.*;
 
public class Main {
 public static void main(String[] args) {
Scanner in = new Scanner(System.in);
        System.out.print("Введите  количество строк: ");
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            int count = 0;
            HashSet<String> test = new HashSet<String>();
            System.out.println("Введите строку: ");
            String s = in.nextLine();
            String s = in.nextLine();
            String[] parts = s.split(" ");
            String first = parts[i];
            parts[i] = parts[parts.length - 1];
            parts[parts.length - 1] = first;
            String result = String.join(" ", parts);
            System.out.println(result);
}
}
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2020-11-27
@Sawayadi

Slightly corrected your code:

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Введите  количество строк: ");
        var n = Integer.valueOf(in.nextLine());
        for (int i = 0; i < n; i++) {
            System.out.println("Введите строку: ");
            var s = in.nextLine();
            var parts = s.split(" ");
            var first = parts[i];
            parts[i] = parts[parts.length - 1];
            parts[parts.length - 1] = first;
            var result = String.join(" ", parts);
            System.out.println(result);
        }
    }

S
Sergey Protasov, 2016-10-23
@protasovse

E ~ F { Описание правил стиля }
The tilde character (~) is used to control the style of sibling elements and is added between the two selectors E and F. The spaces around the tilde are optional. This style is applied to an F element if it has the same parent as the E element and immediately follows it.
HTML send

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question