尝试编写一个程序,提示用户输入文件名。然后它应该从输入文件中读取整数序列,并打印出整数,删除连续出现的重复值。例如,如果输入文件包含1 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1 1 1,则您的程序应打印出1 2 1 5 1 7 1。
我的代码
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++;
}
}
}
}
预期输出为输入文件名:[1,2,1,5,1,7,1] 我得到这个输出输入文件名:1 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1 1 1
我不确定如何删除重复的值,但是没有学会如何使用set,所以试图找到一种不同的方式,任何帮助都会很棒:)
答案 0 :(得分:1)
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++;
}
}
}
}
答案 1 :(得分:0)
由于您的问题并未完全删除可能已使用Set的重复项,因此您只想删除连续的重复项。因此,您必须跟踪当前的int并将其与下一个内联进行比较,如果匹配则跳过它,否则将其添加到列表中。
以下代码显示了如何执行此操作。你可以用这个替换你的while循环:
List<Integer> uniques = new ArrayList<Integer>();
while(inputStream.hasNextInt()) {
int num = inputStream.nextInt();
if(uniques.isEmpty()) {
uniques.add(num);
} else {
if(num!=uniques.get(uniques.size()-1)) {
uniques.add(num);
}
}
}
System.out.println(Arrays.toString(uniques.toArray()));
希望这有帮助。