A
A
akela992020-12-15 14:59:24
Java
akela99, 2020-12-15 14:59:24

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

The problem is to count 2 indexes for swap, because scanner.nextInt() only reads the first digit. Then I read it as a String, split it into an array, and pass the array elements as arguments to the swap method.

Code throws when entering indexes
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 + " ");
            }
        }   
    }

I looked into the solution. Answer:
for (int i = 0; i < swapNum; i++) {
   Collections.swap(list, scanner.nextInt(), scanner.nextInt());       
}


1 - Why is the code throwing Exception ? How does the scanner read information?
2 - Why in the solution scanner.nextInt() reads both digits separated by a space, and not just the first digit ?

====
1 question per question

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-12-15
@akela99

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 question

Ask a Question

731 491 924 answers to any question