Modify your PromptNumbers program from the previous exercise so that it uses a s
ID: 3677287 • Letter: M
Question
Modify your PromptNumbers program from the previous exercise so that it uses a static method to print the elements in forward order and another static method to print the array elements in backward order. The program's behavior should be the same as before.
public class PromptNumbers2 {
public static void main(String[] args) {
int count = console.nextInt();
int[] nums = new int[count];
System.out.println("Your numbers in forward order:");
printForward(nums);
System.out.println("Your numbers in backward order:");
printBackward(nums);
}
// Prints the elements of the given array in forward order.
public static void printForward(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
// Prints the elements of the given array in backward order.
public static void printBackward(int[] a) {
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}}}
Explanation / Answer
Solution
package com.nancy.chegg.qa;
import java.util.Scanner;
public class PromptNumbers2 {
public static void main(String[] args) {
//use scanner to take input from user.
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers will you enter?");
//read int value here
int count = scan.nextInt();
int[] nums = new int[count];
//ask user for inputs
for (int i = 0; i < count; i++) {
System.out.println("Type a number:");
nums[i] = scan.nextInt();
}
System.out.println(" Your numbers in forward order:");
printForward(nums);
System.out.println("Your numbers in backward order:");
printBackward(nums);
scan.close();
}
// Prints the elements of the given array in forward order.
public static void printForward(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
// Prints the elements of the given array in backward order.
public static void printBackward(int[] a) {
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}
}
}
Sample run:
How many numbers will you enter?3
Type a number:33
Type a number:22
Type a number:77
Your numbers in forward order:
33
22
77
Your numbers in backward order:
77
22
33
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.