ross.c ross.c - 4 months ago 27
Java Question

removing duplicate integers from a file

Trying to write a program that prompts the user to enter a filename. It then should read in a sequence of integers from the input file, and print out the integers, removing repeated values that appear consecutively. e.g., if the input file contains 1 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1 1 1 1, your program should print out 1 2 1 5 1 7 1.

My code

import java.util.Scanner;
import java.io.*;



public class Duplicate {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a filename: ");
String fileName = keyboard.nextLine();
if (fileName.equals("")) {
System.out.print("Error: User did not specify a file name.");
} else {
Scanner inputStream = null;

try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("File couldn't be found");
System.exit(0);
}

String[] address = new String[100];

int i = 0;
while (inputStream.hasNextLine()) {
String email = inputStream.nextLine();
// System.out.println(email);

address[i] = email;
System.out.println(address[i]);
i++;


}
}
}
}


The expected output is Enter a filename: [1, 2, 1, 5, 1, 7, 1]
I get this output Enter a filename: 1 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1 1 1 1

I'm not sure how to remove the duplicate values, Havn't learnt how to use set so trying to find a different way any help would be great :)

Answer
public class Duplicate {
   public static void main(String[] args) {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Enter a filename: ");
   String fileName = keyboard.nextLine();
   if (fileName.equals("")) {
      System.out.print("Error: User did not specify a file name.");
   } 
   else {
     Scanner inputStream = null;
    try {
        inputStream = new Scanner(new File(fileName));
    } 
    catch (FileNotFoundException e) {
       System.out.println("File couldn't be found");
       System.exit(0);
    }

   String[] address = new String[100];
   int i = 0;
       while (inputStream.hasNextLine()) {
           String email = inputStream.nextLine();
           // System.out.println(email);
            address[i] = email.replace(" ", "")+" ";// add a space at the end of the line

          char ch1,ch2; //Variables to compare charachters
          String result ="";//Variable to store the final result
           for(int j=0; j<address[i].length()-1; j++){
               ch1=address[i].charAt(j); // get the first character
               ch2=address[i].charAt(j+1); // get the next character 
              if(ch1!=ch2) {// compare first and second, second and third ..., and so on; if not equal add to result            
              result = result + ch1;
              }
            }
          char [] res = result.toCharArray();
          System.out.println(Arrays.toString(res)); // Printing the result
          i++;
      }
    }
  }  
}