Input - Help

Input

My code
Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();
        while (t-- > 0)
        {
            int N = sc.nextInt();
            int K = sc.nextInt();
            char[] arr = new char[N];
            for (int i = 0; i < arr.length; i++)
            {
                arr[i] = sc.next().charAt(0);
            }
        }

am I right?

This is a common problem for people starting CP in Java.
Refer: Why is scanner skipping nextline after nextint

Edit: TL;DR When you use nextint, the cursor does not go to the next line, but stays at the end of the int. So, you have to add a nextline before using nextline again for taking input to shift the cursor to the new line.

Nope.
When there is a String with length N and if you want to store it as a Character array, use the following code.

int N = sc.nextInt();
int K = sc.nextInt();
char arr[] = sc.next().toCharArray();

Corresponding input:

5 3
abcab

Likewise, if the input is a sequence of space-separated characters, the following code is used.

int N = sc.nextInt();
int K = sc.nextInt();
char arr[] = new char[N];
for(int i = 0; i < N; i++) {
    arr[i] = sc.next().charAt(0);
}

Corresponding Input (Notice the space between characters):

5 3
a b c a b

Thank you Suman!

1 Like
        // create a scanner
        Scanner sc = new Scanner(System.in);
        
        int t = sc.nextInt();
        while (t-- > 0)
        {
            int N = sc.nextInt();
            int K = sc.nextInt();
            char[] arr = sc.next().toCharArray();
        }

Variable N is not used. What if I input the length of a string greater than N?

How about this code snippet?
// create a scanner
Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();
        while (t-- > 0)
        {
            int N = sc.nextInt();
            int K = sc.nextInt();
            String s;
            do
            {
                s = sc.next();
            } while (s.length() != N);
}

Yeah, it is useful when you’re iterating over String. Like this:

while(t--  > 0) {
    int N = sc.nextInt();
    int K = sc.nextInt();
    char arr[] = sc.next().toCharArray();
    for(int i = 0; i < N; i++) {
        if(arr[i] == 'a') {
            // do something here
        }
    }
}

The following helps

char arr[] = sc.next().toCharArray();
int length = arr.length; // To find the length of string
for(int i = 0; i < length; i++) {
    // some code here
}

This is so dumb. There is no sense in doing that.