guesswordwithfiledict.java
来自「这个程序是基于JAVA的JBUILDER的一个很使用的猜词程序」· Java 代码 · 共 72 行
JAVA
72 行
import java.io.*;
class WordDictionaryInFile{
private int index=-1;
private int wordCount=0;
private String[] words;
WordDictionaryInFile(String fileName){
String word;
words=new String[100];
try{
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
while(true){
word=br.readLine();
if(word==null)
break;
words[wordCount++]=word;
if(wordCount>=words.length){ //words满,需要动态扩展,每次都扩展成原来长度的一倍
String[] tmp=new String[words.length];
for(int i=0;i<tmp.length;i++)
tmp[i]=words[i];
words=new String[words.length*2];
for(int i=0;i<tmp.length;i++)
words[i]=tmp[i];
}
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("词库共有"+wordCount+"个单词,加油啊...");
}
public String getMagicWord(){
int i=(int)(Math.random()*wordCount);
index=i;
return convertWord(words[i]);
}
private String convertWord(String word){
char[] charsInWord=word.toCharArray();
for(int i=charsInWord.length-1; i>0; i--)
for(int j=0; j<i; j++)
if ( charsInWord[ j ] > charsInWord[ j+1 ] ){
char temp=charsInWord[ j ];
charsInWord[ j ]=charsInWord[ j+1 ];
charsInWord[ j+1 ]=temp;
}
return new String(charsInWord);
}
public String getOriginalWord(){
return words[index];
}
}
class GuessWord{
public static void main(String args[]){
WordDictionaryInFile wd=new WordDictionaryInFile("四级.txt");
int guessTimes=0,correctTimes=0;
while(true){
System.out.println("猜猜这是什么单词:"+wd.getMagicWord());
guessTimes++;
if(wd.getOriginalWord().equals(KeyInput.readString())){
System.out.println("对了,就是 "+wd.getOriginalWord());
correctTimes++;
}
else
System.out.println("错了,是 "+wd.getOriginalWord());
System.out.print("继续玩吗?(y/n)");
if(KeyInput.readString().toLowerCase().equals("n"))
break;
}
System.out.println("猜对率为"+(correctTimes*100/guessTimes)+"%,拜拜喽...");
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?