JAVA课堂测试之单词接龙

  在input.txt中输入几个随机相接的单词例如Apple Zoo Elephant Under Fox Dog Moon Leaf Tree。

在代码中读取

File f = new File("input.txt");
FileInputStream fip = new FileInputStream(f);
InputStreamReader reader = new InputStreamReader(fip, "gbk");
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
list.add((int) ch((char) reader.read()));
// sb.append(ch((char) reader.read()));
}
// System.out.println(sb.toString());

函数ch()将每个字母变成小写字母。

static char ch(char c)
{
if(!(c>=97&&c<=122))
c+=32;
return c;
}

定义动态数组list来获取每个字母;

在定义动态数组list1来获取每个空格键在list中的位置。

int temp1=0;
String num="";
for(int i=0;i<9;i++)
{
if(i==0)
{
System.out.print(c[0]);
num=c[0];
}
for(int k=i+1;k<9;k++)
{
if(c[temp1].charAt(c[temp1].length()-1)==c[k].charAt(0))
{
System.out.print("-"+c[k]);
num+="-"+c[k];
temp1=k;
break;
}
}
}

来获取并输出接龙。

附上源码:

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class find {
public static void main(String []args) throws IOException
{
System.out.println("文章为:");
List<Integer> list=new ArrayList<>();
List<Integer> list1=new ArrayList<>();
Scanner scan=new Scanner(System.in);
File f = new File("input.txt");
FileInputStream fip = new FileInputStream(f);
InputStreamReader reader = new InputStreamReader(fip, "gbk");
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
list.add((int) ch((char) reader.read()));
// sb.append(ch((char) reader.read()));
}
// System.out.println(sb.toString());
Object[]a=list.toArray();
for(int i=0;i<list.size();i++)
{
if((char)(int)a[i]=='@')
{
list1.add(i);
}
}
reader.close();
fip.close();
Object[]b=list1.toArray();
String []c=new String[9];
c[0]=""; c[1]=""; c[2]=""; c[3]=""; c[4]=""; c[5]=""; c[6]=""; c[7]=""; c[8]="";
int temp=0;
for(int i=0;i<list.size();i++)
{

// if(((char)(int)a[i]==(char)(int)a[(int)b[temp]-1])&&((char)(int)a[i-1]=='@'))
// {
// for(int k=(int)b[temp]+1;k<(int)b[temp+1];k++)
// {
// System.out.print((char)(int)a[k]);
// }
// }
if((char)(int)a[i]!='@')
{
c[temp]+=(char)(int)a[i];
}
if((char)(int)a[i]=='@')
{
temp++;
}
}
int temp1=0;
String num="";
for(int i=0;i<9;i++)
{
if(i==0)
{
System.out.print(c[0]);
num=c[0];
}
for(int k=i+1;k<9;k++)
{
if(c[temp1].charAt(c[temp1].length()-1)==c[k].charAt(0))
{
System.out.print("-"+c[k]);
num+="-"+c[k];
temp1=k;
break;
}
}
}

FileWriter fw = null;
try {
//创建字符输出流
fw = new FileWriter("output.txt");
fw.write("'"+num+"'\r\n");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
//使用finally块来关闭文件输出流
if (fw != null) {
fw.close();
}
}
}
static char ch(char c)
{
if(!(c>=97&&c<=122))
c+=32;
return c;
}
}

猜你喜欢

转载自www.cnblogs.com/jccjcc/p/10986762.html