I'm a beginner. I solved the 1st classical on Spoj. But the first code i wrote couldn't solve the exercise because 42 is included in the output. The second code solved the problem because it doesn't print 42. But i still can't figure out how it works. Why does Code A prints 42 and why doesn't Code B? Please help me out!
Code A
public class CodeA {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
int n = 0;
while(true) {
if(n!=42) {
n = input.nextInt();
System.out.println(n);
}
else{
break;
}
}
}
}
Code B
public class CodeB {
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
while(true) {
int n = in.nextInt();
if(n == 42) {
break;
}
System.out.println(n);
}
}
}
Aucun commentaire:
Enregistrer un commentaire