gpt4 book ai didi

java - 从文件中删除重复的整数

转载 作者:行者123 更新时间:2023-12-01 09:36:36 25 4
gpt4 key购买 nike

尝试编写一个程序来提示用户输入文件名。然后,它应该从输入文件中读取整数序列,并打印出整数,删除连续出现的重复值。例如,如果输入文件包含 1 2 2 1 5 1 1 7 7 7 7 1 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++;


}
}
}
}

预期输出为 Enter a filename: [1, 2, 1, 5, 1, 7, 1]我得到这个输出 Enter a filename: 1 2 2 1 5 1 1 7 7 7 7 1 1 1 1 1 1 1 1 1

我不确定如何删除重复值,还没有学会如何使用 set,因此尝试找到不同的方式任何帮助都会很棒:)

最佳答案

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++;
}
}
}
}

关于java - 从文件中删除重复的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com