5) (15 marks) Write a Java program named a1q5.java which reads positive integers
ID: 3751212 • 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
Please find the Java code below.
CODE
===============
import java.util.ArrayList;
import java.util.Scanner;
public class a1q5 {
public static void main(String args[]) {
int input;
ArrayList<Integer> in = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter postive numbers ( <= 0 to exit) : ");
while(true) {
input = sc.nextInt();
if (input > 0)
in.add(input);
else
break;
}
for(int i = 1; i < in.size(); i += 2) {
System.out.println(in.get(i));
}
System.out.println("-1");
}
}
NOTE: I am not very sure of the pipeline command. Hence, requesting you to post the problem b) separately to get the correct answer. Sorry for the inconvenience caused.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.