5) (15 marks) Write a Java program named a1q5.java which reads positive integers
ID: 3751021 • Letter: 5
Question
5) (15 marks) Write a Java program named a1q5.java which reads positive integers from the input and prints every second integer to the output. The program stops when it reads the first negative integer or zero, without printing it. However, the program must also print a -1 at the very end Input: The input consists of a sequence of integers, one integer per line, where all integers are positive except the last one. For example, the input could be 7 3 2 Output: The output will also consists of a sequence of integers, which consists of each second positive integer from the input, with the final line containing -1. For example, the output of the above input must be 3 2 -1Explanation / Answer
import java.util.Scanner;
public class A1q5 {
public static void main(String []args) {
int a,b;
boolean flag;
Scanner in = new Scanner(System.in);
while(true) {
flag = false;
a = in.nextInt();
if(a <= 0) {
System.out.println("-1");
}
b = in.nextInt();
if(a <= 0) {
System.out.println("-1");
}
System.out.println(b);
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.