The problem is, I have to print NO
if given array have any Even element and YES
if all elements is Odd,
but if my code print NO
after that it will only print NO
.
Given
t
= Total test case
n
= Length of each arrayand of course
n
elements also
Input
2
5
1 2 5 4 3
1
7
Output
NO
NO
Expected Output
NO
YES
Following is My Code
import java.util.Scanner;
public class dsj {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0){
int n = sc.nextInt();
boolean k = true;
for (int i = 0; i < n; i ) {
int x = sc.nextInt();
if (x % 2 == 0) {
k = false;
break;
}
}
if (k)
System.out.println("YES");
else
System.out.println("NO");
}
sc.close();
}
}
Please tell me what I am doing wrong
CodePudding user response:
As soon as your application find an even number it breaks the loop, which means it no longer reads the rest of the line. The next invocation will start where the previous left off and consume that input.
So when the second '2' is read, the inner loop breaks and 'NO' gets printed. For the next loop the '5' is read which means there should be 5 values to be read. Then the value '4' is read, which is even again, and the code emits 'NO' again. The values 3, 1 and 7 are never consumed.
It works as designed. To better understand, add lots of System.out.println statements, or learn how to use a debugger.
But to answer your question:
The first int specifies how many datasets you want to read. The first int per dataset specifies how many data values are in the set. The remaining numbers resemble the data set.
Your problem is that when you encounter an even number you do not read the remainder of the dataset, and you program treats the next integers as the specifier of the next dataset's length.
What you need to change is that even when you encountered an even number you have to consume enough integers from your scanner so the dataset is read before you start reading the next.
That change can be as easy as removing the break
.
CodePudding user response:
after you print yes or no, you should reset the boolean to true again
EDIT: @Suman Saurabh is correct here