Reputation: 173
Write a main method that asks the user for an integer
n
which then allocates an array of ints of that size and stores that many integers as the user enters them. Once they are all entered, print them in the reverse order of how they were entered.
This is what I have come up, thus far (any help will be greatly appreciated):
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Array2D {
public static void main(String[] args){
Scanner num = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
int ber = 0;
String stop = "";
System.out.println("Type as many number as you like, to get in reverse order. When done typing number, type STOP: ");
do{
try{
ber = num.nextInt();
number.add(ber);
}
catch(InputMismatchException e){
stop = num.nextLine();
e.equals(stop);
}
}while(!(stop.equalsIgnoreCase("stop")));
Upvotes: 0
Views: 97
Reputation: 173
int n = 0;
Scanner num = new Scanner(System.in);
System.out.println("How many numbers do you want to display: ");
n = num.nextInt();
int[] number = new int[n];
System.out.println("Enter the numbers: ");
for(int i = 0; i<n; i++){
number[i] = num.nextInt();
}
System.out.println("Here they are in reverse! ");
for(int i = n-1; i >= 0; --i){
System.out.println(number[i]);
}
Upvotes: 2
Reputation: 4037
Change the catch to :
catch (InputMismatchException e) {
if(stop.equalsIgnoreCase("stop")){
continue;
}
stop = num.nextLine();
e.equals(stop);
}
And for printing them in reverse order:
for (int i= (number.size()-1); i >= 0; i--) {
System.out.println(number.get(i));
}
Upvotes: 2
Reputation: 124215
Task from your question is asking you to do something like this (there is no even need to handle case where user writes stop
or other incorrect data, but you can handle them if you want).
//ask user for array size
int n = getInt();
//create array for n integers
int[] array = new int[n];
//read n integers from user
for (i in 0..n-1)
tmp = readInt()
//and store them in array
put tmp in array at position i
//print content of array backwards
for (i in n-1..0)
print(i-th element from array)
Upvotes: 1
Reputation: 475
print them in the reverse order
for (int i = number.size() - 1; i >= 0; i--) {
System.out.println(number.get(i));
}
Upvotes: 1
Reputation: 224
You do not need arraylist for the problem statement. Just the basic code logic using arrays.
void print reverse(int n){
int[] arr = new int[n];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < n; ++i){
arr[i] = sc.nextInt();
}
for (int i = n-1; i >= 0; --i){
System.out.println(arr[i]);
}
}
Upvotes: 1