在OOP入门课程中,我必须制作一个莫尔斯电码翻译器。它需要在中读取文本文件,并使用该文件来匹配莫尔斯电码翻译的用户输入。我的问题在于,一旦我输入了用户输入,它就会返回一个null值,而不是莫尔斯电码翻译。
public static void main(String[] args) throws FileNotFoundException, IOException {
//File file = new File(new FileReader("C:\Users\myNAme\Desktop\morse.txt");
Scanner scan = new Scanner(new FileReader("C:\Users\myName\Desktop\morse.txt"));
Scanner input = new Scanner(System.in);
HashMap<String, String> morse = new HashMap<String, String>();
while (scan.hasNextLine())
{
String[] columns = scan.nextLine().split(" ");
morse.put(columns[0],(columns[1]));
}
System.out.println(morse);
System.out.println("What do you want to translate into morse code?: ");
String eng2morse = input.nextLine();
eng2morse = eng2morse.toUpperCase();
System.out.print(morse.get(eng2morse));
}
}
我在这个项目上挣扎了一段时间,我只是想看看我做错了什么,以及如何修复它
文本文件(morse.txt(
A。-
B-。。。
C-.-。
D。。
E。
F…-。
G-。
H。。。。
我。。
J.---
K-.-
我。。
M——
N-。
O--
p.--。
Q————
R-。
S。。。
T-
U…-
V…-
W.--
X-..-
Y---
Z。。
1.----
2.---
3…--
4
5。。。。。
6-。。。。
7--。。。
8--。。
9-----。
0-----
/。
+.-.-。
=-…-
,--..--
。。
(-.--.
)-.--.-
--……-
".-...
_
"。
:---。。。
;-.-.-。
$…-…-
可能有以下原因:
- 修剪用户的输入
- 在放置column[0]的同时对其进行修剪,并使用toUpperCase((方法作为用户输入
更改
morse.put(columns[0],columns[1]);
至
morse.put(columns[1].trim(),columns[0].trim());