- My code creates the 'list' array and reads the required 5 elements from the keyboard into the list.
- It iterates 13 times through the list by adding the last list element at the beginning of the list and then removing the last element from the resulting array.
- All 5 members of the resulting list are printed on a new line.
The result concurs with the manual substitution process.
Nevertheless, the code does not validate.
Has anyone an idea, why it does not fulfill the last 2 requirements?
0: grandfather, grandmother, daughter, program, car
1: car, grandfather, grandmother, daughter, program
2: program, car, grandfather, grandmother, daughter
3: daughter, program, car, grandfather, grandmother
4: grandmother, daughter, program, car, grandfather
5: grandfather, grandmother, daughter, program, car
6: car, grandfather, grandmother, daughter, program
7: program, car, grandfather, grandmother, daughter
8: daughter, program, car, grandfather, grandmother
9: grandmother, daughter, program, car, grandfather
10: grandfather, grandmother, daughter, program, car
11: car, grandfather, grandmother, daughter, program
12: program, car, grandfather, grandmother, daughter
package com.codegym.task.task07.task0711;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Remove and insert
*/
public class Solution {
public static void main(String[] args) throws Exception {
//1. Create a list of strings.
ArrayList<String> list = new ArrayList<>();
//2. Add 5 strings from the keyboard.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 5; i++) {
String s = reader.readLine();
list.add(s);
}
//3. Do the following 13 times: remove the last string and insert it at the beginning.
for (int k = 0; k < 12; k++) {
list.add(0, list.get(4)); // fetch the last value and insert it at the beginning of the list
list.remove(5); // remove the last value
}
//4. Use a loop to display the resulting list, each value on a new line.
for (int j=0; j<5; j++) {
System.out.println(list.get(j));
}
}
}