Create a program that displays the five numbers you entered in reverse order. Requirements
Please enter 5 numbers
1>10
2>20
3>30
4>40
5>50
num[4] = 50
num[3] = 40
num[2] = 30
num[1] = 20
num[0] = 10
Check51.java
package practice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Check51 {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter 5 numbers");
String line;
try {
ArrayList<Integer> nums = new ArrayList<Integer>();
for( int i = 1; i <= 5; i++) {
System.out.print(i+">");
line = reader.readLine();
int num = Integer.parseInt(line);
nums.add(num);
}
for( int i = 5; i > 0; i--) {
int j = i-1;
System.out.println("num["+j+"] = "+nums.get(j));
}
} catch (NumberFormatException e) {
System.out.println("Please enter an integer");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I don't think it's smart to subtract 1 from i in for. .. The array starts at 0, so it wouldn't be clean without this.
Recommended Posts