Answer to Question #293850 in Java | JSP | JSF for Hag

Question #293850

Task #4: Arrays, Methods and File I/O

2. Write another method called getSecondLargestNumber that accepts an integer array 

as argument and returns the second largest number from the array.

You may use the following header for this method:

static int getSecondLargestNumber(int[] array)

For example, if we pass {10, 17, 3, 5, 12, 19} then the method should return 

17 as the second largest number from the array.

NOTE: Read the input from the input-4-3.txt file.

 Write the output to the output-4-3.txt file.

 Write the second smallest and then the second largest number from that array.

1. Create a program called FileIOSecondSmallestLargestLab3.java. 

2. Correctly write the output with appropriate messages..


1
Expert's answer
2022-02-04T14:50:01-0500


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


class FileIOSecondSmallestLargestLab3 {


	static int getSecondLargestNumber(int[] array) {
		int temp;
		for (int i = 0; i < array.length; i++) {
			for (int j = i + 1; j < array.length; j++) {
				if (array[i] > array[j]) {
					temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
			}
		}
		return array[array.length - 2];
	}


	public static void main(String[] args) {
		int array[] = new int[100];
		try {


			Scanner input = new Scanner(System.in);
			File file = new File("input-4-3.txt");
			input = new Scanner(file);
			int counter = 0;
			while (input.hasNextLine()) {
				String line = input.nextLine();
				array[counter] = Integer.parseInt(line);
				counter++;
			}
			input.close();


		} catch (Exception ex) {
			ex.printStackTrace();
		}


		int secondLargestNumber = getSecondLargestNumber(array);


		try {
			FileWriter fWriter = new FileWriter("output-4-3.txt");
			fWriter.write("" + secondLargestNumber);
			fWriter.close();


		}
		// Catch block to handle if exception occurs
		catch (IOException e) {
			// Print the exception
			System.out.print(e.getMessage());
		}


	}
}


 input-4-3.txt file:







Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS