尝试编写一个提示用户输入文件名的程序。然后,它应该从输入文件中读取整数序列,并打印出整数,删除连续出现的重复值。例如,如果输入文件包含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++;
}
}
}
}
预期的输出是输入文件名:[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 1个
我不确定如何删除重复的值,Hav还没有学习如何使用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++;
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句