Arrays, Methods and File I/O
In this task, you are being asked to write methods that manipulate arrays, and write and read to
and from the text file in Java.
Write a method called getFirstRepeatingNumber that accepts one integer array as
argument and returns the first repeating number from the array.
For example, if we pass {3, 5, 6, 2, 7, 9, 8, 11, 6, 12} then the method should
return 6 as the first repeating element from the array. If all the elements are unique, then the method
should return -1.
You may use the following header for this method:
static int getFirstRepeatingNumber(int[] array)
Declare and initialize the array and write the first repeating number from that array in the output file. If there is no repeating element in the array, then you would write “All elements are unique”by a test in the main method.
Read the input from the input-3-3.txt file.
Write the output to the output-3-3.txt file.
Create a program called FileIOFirstRepeatingNumberLab3.java.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
class FileIOFirstRepeatingNumberLab3 {
static int getFirstRepeatingNumber(int[] array) {
int c = 0;
for (int j = 1; j < array.length; j++) {
if (array[0] == array[j]) {
c++;
}
}
if (c == array.length - 1) {
return -1;
}
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
return array[i];
}
}
}
return -1;
}
public static void main(String[] args) {
int array[] = new int[100];
try {
Scanner input = new Scanner(System.in);
File file = new File("input-3-3.txt");
input = new Scanner(file);
int c = 0;
while (input.hasNextLine()) {
String line = input.nextLine();
array[c] = Integer.parseInt(line);
c++;
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
int uniqueNumber = getFirstRepeatingNumber(array);
try {
FileWriter fWriter = new FileWriter("output-3-3.txt");
if (uniqueNumber == -1) {
fWriter.write("All elements are unique");
} else {
fWriter.write("" + uniqueNumber);
}
fWriter.close();
}
// Catch block to handle if exception occurs
catch (IOException e) {
// Print the exception
System.out.print(e.getMessage());
}
}
}
Comments
Leave a comment