Problem:
To solve this assignment, you are supposed to know file
input/output (reading from and writing to a file) and array list usage.
First,
fill an input file called input.txt with 12 numbers: 4 6 8 3 1 2 3 9
8 4 3 0 (each integer on a line).
In your
main method, read these items from the input file, fill them in an integer
array list, and write them to an output file called output.txt after
concatenating each of them with the corresponding index.
The content of the output file will be:
4 0
6 1
8 2
3 3
1 4
2 5
3 6
9 7
8 8
4 9
3 10
0 11
Then,
remove the item at index 6 from the array list and the print on the console (on
the screen using System.out.println(..)) the size of that array list
(which is supposed to be 11 now) on one line, the array list items on the next
line, and the sum of the items on the last line.
The
printed output on the screen must be: 11
4 6 8 3 1 2 9
8 4 3 0
48
Solution:
/**-------------------ExerciseII.java---------------------------*/ import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Formatter; import java.util.Scanner; public class ExerciseII { public static void main(String[] args) throws FileNotFoundException { //Calling the input.txt file with 12 numbers from memory Scanner scan = new Scanner(new File("input.txt")); //Creating an array list ArrayListarrayList = new ArrayList (); //Filling the 12 numbers in the arrayList while (scan.hasNext()) arrayList.add(scan.nextInt()); //Creating output.txt file Formatter input = new Formatter("output.txt"); //Filling the output.txt with required content for (int i = 0 ; i < arrayList.size(); i++) input.format(arrayList.get(i) + " " + i + "%n"); //Closing output.txt input.close(); //Removing item at index 6 from the array list arrayList.remove(6); //Printing arrayList size System.out.println(arrayList.size()); //Printing arrayList content for (int i = 0 ; i < arrayList.size();i++) System.out.print(arrayList.get(i) + " "); System.out.println(); //Printing sum int sum = 0; for (int i = 0 ; i < arrayList.size();i++) sum += arrayList.get(i); System.out.println(sum); } } /**-------------------input.txt---------------------------*/ 4 6 8 3 1 2 3 9 8 4 3 0 /**-----------------output.txt---------------------------*/ 4 0 6 1 8 2 3 3 1 4 2 5 3 6 9 7 8 8 4 9 3 10 0 11
liposuction surgery Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.
ReplyDelete