我要读取Java中包含以下内容的文件:
.- ... ... .. --. -. -- . -. - ....-
.. ...
..-. .. -. .- .-.. .-.. -.--
-.. --- -. .
关键是要读取整个文件,但第一行的前两个字符除外,并且仅打印:
.....--。 - -。 - -....-
代替
.- ... ... ..- - -。 - -....-
如何读取此txt文件的第一个字符?
这是代码:
String line = "";
String []split;
Scanner scanner = new Scanner (System.in);
System.out.print("Input file:");
String inputFile = scanner.nextLine();
File file = new File(inputFile);
Scanner input = new Scanner(file);
String [] alphabet = {
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","W","X","Y","Z"
,"0","1","2","3","4","5","6","7","8","9"};
String [] morse = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..",
"-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----."};
if(input.hasNext())
input.next();
while(input.hasNextLine()){
line = input.nextLine();
split = line.split("\t");
System.out.println(split[0]);
for (int i = 0; i < split.length; i++){
}
}
}
}
最佳答案
if(input.hasNext()) input.next();
为什么要这样做?它读取第一个字符串“ .-”。您正在读取字符串,但未将其分配给任何变量。
只需删除部分代码,即可在while循环中读取此字符串。