Answer the question
In order to leave comments, you need to log in
How does Java Scanner work in this situation?
How does Java Scanner work in this situation?
There is a task.
Enter multiple elements for the array.
Enter how many permutations to make (swap).
Enter which indexes in the array to rearrange.
Print result.
Пример
Input:
1 2 3 4 5 6
2
0 1
3 5
Output: 2 1 3 6 5 4
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
ArrayList<String> list = new ArrayList<>(Arrays.asList(input.split(" ")));
int swapNum = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < swapNum; i++) {
String[] swap = scanner.nextLine().split(" ");
int first = Integer.parseInt(swap[0]);
int second = Integer.parseInt(swap[1]);
Collections.swap(list, first, second);
}
for (String item : list) {
System.out.print(item + " ");
}
}
}
for (int i = 0; i < swapNum; i++) {
Collections.swap(list, scanner.nextInt(), scanner.nextInt());
}
Answer the question
In order to leave comments, you need to log in
You overdone something in the cycle. It's a little easier there:
for (int i = 0; i < swapNum; i++) {
var first = scanner.nextInt();
var second = scanner.nextInt();
Collections.swap(list, first, second);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question