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);
}
}
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.
// 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?
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
}