编程实现一个命令窗程序,使得:
- 输入“你”则在屏上回显“you”。
- 输入“书”则在屏上回显“Book”。
- 输入“中”则在屏上回显“middle”。
- 输入“中国”则在屏上回显“China”。
- …要能输入至少100个词。如输入没有记录的词则如下:
- 输入“东东”则在屏上回显“查不到该词”。
- 输入ByeBye则退出程序.
- (提示: 单词字典应做一个文本文件读入,其中每行为:<中文字词><对应英文> )
- 如:字典文件 dic.txt内容是
- <我>
- <你>
- <中国>
- ……
代码
package day01;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Demo06 {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("请输入一个词:");
String str = scan.nextLine();
FileReader fr = new FileReader("dic.txt");//创建一个新的 FileReader,给予File读。
BufferedReader br = new BufferedReader(fr);//从一个字符输入流中读取文本
String s = null;//定义一个字符串
boolean b = false;//判断字典中是否含有输入的词
while((s = br.readLine()) != null) {//readLine()读一行文本
//substring(int beginIndex, int endIndex)
//返回一个字符串的子串,相当于剪切,从beginIndex开始到endIndex结束(含头不含尾)
//indexOf(String str)
//返回指数在这个字符串指定的子字符串中第一个出现的下标。
String china = s.substring(s.indexOf("<")+1, s.indexOf(">"));
//lastIndexOf(String str)
//返回指数在这个字符串的指定子字符串中最后出现的下标。
String english = s.substring(s.lastIndexOf("<")+1,s.lastIndexOf(">"));
if(str.equals(china)) {//存在
System.out.println(english);
b = true;
}
}
if(str.equals("ByeBye")) {//判断是否输入的为"ByeBye"
System.out.println("程序退出!");
System.exit(0);//终止当前正在运行的java虚拟机
}
if(!b) {//查不到
System.out.println("查不到该词!");
}
}
}
}
dic.txt内容以及位置


运行结果
