实验题汇总
1、public class Stairs
{ public static final int SIZE=8;
public static void main(String[] args)
{
for (int i=1;i<=SIZE;i++){
for (int j=1;j<=5(SIZE-i);j++) System.out.print(“ “);
System.out.print(“ O **“);
kongge(i);
System.out.println(““);
for (int k=1;k<=5(SIZE-i);k++) System.out.print(“ “);
System.out.print(“ /|\ “);
kongge(i);
System.out.println(““);
for (int m=1;m<=5(SIZE-i);m++) System.out.print(“ “);
System.out.print(“ / \ “);
kongge(i);
System.out.println(““);
}
for (int h=1;h<=5(SIZE+1)+2;h++) System.out.print(““);
}
public static void kongge(int line){
for (int g=1;g<=5(line-1);g++) System.out.print(“ “) }
}
这是打印楼梯的程序,主要就是循环和一个全局变量的使用
2、public class Calendar
{ public static final int Date=8;
public static final int Day=31;
public static void main(String[] args){
System.out.println(“ Sun Mon Tue Wed Thu Fri Sat “);
liner();
int m=8-Date;
for (int i=1;i<=m;i++) System.out.print(“| “);
for (int d=1;d<=Day;d++)
{
if ((d/10)<1) System.out.print("| ");
else System.out.print(“| “);
System.out.print(d);
System.out.print(“ “);
if ((d+m)%7==0) { System.out.print(“|”);
System.out.println();} }
int h=7-((Day+m)%7);
for (int i=1;i<=h;i++) System.out.print(“| “);
System.out.print(“|”);
System.out.println();
liner();}
public static void liner()
{ for (int i=1;i<=7;i++) System.out.print(“+———“);
System.out.print(“+”);
System.out.println()}}
这是打印日历的题目,注意补空和数字的变化
3、**import java.util.;**//Scanner类必须要有的
public class guess{
public static void main(String[] args)
{ Scanner console = new Scanner(System.in);**//从键盘获取数据
System.out.println(“This program has you,the user,choose a number”);
System.out.println(“between 1 and 10,then I,the computer,will try my best to guess it. “);
int time=0;
String c;
do{ time=time+1;
Random random = new Random();
int d=random.nextInt(10);
System.out.print(“Is it “+d+”?”);
//Scanner类没有提供直接接收一个字符的方法,这里当作字符串来接收;
c=console.next();
}while (c.equals(“n”));
//字符串的相等不能直接使用==;
//注意定义的顺序, String c;必须要在循环的外面定义,否则在循环运行的过程中会认为没有这个变量。**
System.out.println();
System.out.println(“I got your number of “+(time-1)+” in “+time+” times”); }}
猜数字的题目,计算机产生一个随机数,然后比较输入的数字
- 从键盘读取的方法,以及字符串的一系列比较方法
- 随机数的产生
4、import java.util.;
public class PRS{
//对于这种玩游戏的题目,可以给后来的选项(是否要继续游戏)先赋一个初始值,就是默认是同意再来一局的。
//或者是用 do-while 代替 while。
//这是一个很明智的方法!
public static void main(String[] args)
{String answer=”y”;
while (answer.equals(“y”)) {
System.out.println(“Best out of how many games(must be odd)?”);
**int time=console.nextInt();//**字符的读取要注意
System.out.println();
for (int i=1;i<=time;i++){
char s2=random();
System.out.print(“Choose your weapon?”);
String c2=console.next();
System.out.print(“I choose the weapon:”+s2);
game(c2,s2,a); }
System.out.println(“Do you want to play again?”);
answer=console.next(); //读取下一个字符,再判断 }
result(a);}
public static char random()//产生PSR中的任意一个字符,并且返回这个字符。 { String CHARS = “PRS”;
Random random = new Random();
int d=random.nextInt(3);
//注意随机数函数里的格式使用,(n)表示0-n-1的范围的数。
char c1=CHARS.charAt(d);
return c1;}
public static void game(String c,char s,int a[])
//游戏的开始,就是每一句的胜负判断。
{ if (c.equals(“P”)) { if (s==’P’) { System.out.println(“ Tie!”);
a[0]=a[0]+1; }
if (s==’R’) { System.out.println(“ You win!”);
a[1]=a[1]+1; }
if (s==’S’) {System.out.println(“ You lose!”);
a[2]=a[2]+1;
//字符本身的比较用== }
}
(省略了其他两种情况)
public static void result(int a[])
{ System.out.println();
System.out.println();
int all=a[0]+a[1]+a[2];
double per=a[1]/(all1.0);
System.out.println(“Overall results:”);
System.out.println(“Total games =”+all);
System.out.println(“wins =”+a[1]);
System.out.println(“loses =”+a[2]);
System.out.println(“ties =”+a[0]);
System.out.printf(“win%% =%.1f”,per);
//注意最后有百分号的格式的输出,要加两个百分号! }}
这是 石头剪刀布 的题目 最后的输出一定要注意。
5、import java.util.;
**import java.io.;**//使用文件类需要有的语句
public class Search{
public static void main (String[] args)
throws FileNotFoundException//读文件是必要的语句
{
Scanner input = new Scanner (new File (“names.txt”));
Scanner console = new Scanner(System.in);
//**input是文件扫描器、console是每一行的扫描器
System.out.println(“This program will allows you to search the popularity of your name.”);
System.out.println();
System.out.print(“Name?”);
String name =console.next();//获取一个名字
System.out.println();
boolean flag;
flag=false;//标记是否找到目标
while (input.hasNextLine())//**在文件中一行一行寻找目标
{ String s=input.nextLine();
Scanner scan = new Scanner (s);**//scan是token的扫描器
String s2=scan.next();
if (s2.equals(name))
{ flag=true;
System.out.println(“Static on”+name);
for (int i=0;i<=10;i++){
String popular=scan.next();
int year=1900;
year=year+i*10;
System.out.println(“ “+year+”:”+popular);}}}
if (flag==false) {
System.out.println(“Not found”);}}}
该题目就是在一个文件中,找到指定人的姓名,并且按照年份输出他在每个年代的受欢迎程度。
注意文件基于行的处理和基于token的处理的混合使用**
6、import java.util.;
import java.io.;
public class text{
public static void main (String[] args)
throws FileNotFoundException{
int[] arr = {0,0,0,0};**//这是一个数组的定义方法
System.out.print(“What file do you want me to examine?”);
Scanner console= new Scanner(System.in);
String name=console.next();
Scanner input = new Scanner (new File (name));
while (input.hasNextLine()) //注意hasNextLine和nextLine的书写!
{ arr[0]++;
String s=input.nextLine();
line(s,arr); //这是一个单独的方法**}
double word;
word=(double)arr[1];
word=word/arr[2];
System.out.println(“Total lines:”+arr[0]);
System.out.println(“Total words:”+arr[2]);
System.out.println(“Total chars:”+arr[1]);
System.out.println(“Word length:”+word);}
public static void line(String s1,int arr[]){
String s2; ** // s1是一整行的字符,是一个大的字符串
Scanner scan = new Scanner (s1);** //s2是一个token,是一个小的字符串
while (scan.hasNext()){
s2=scan.next();
arr[1]=arr[1]+s2.length();
arr[2]++; }
arr[3]—; }}
统计一个文本文件中的字符、行数、字符数(不计空格)和文件中所有单词的平均长度。
计算每一行很多很长的整数的和:注意文件的输出和读入
/*对于这个程序,有几个运行时的关键点需要注意
1、就是关于下标越界的问题
s.length()获得的是字符串的实际长度
s作为字符数组,用charAt的时候要注意下标是从0开始的
2、就是字符和数字转换的时候,如果用int强制转换,则必须要注意值的改变,字符-48=数字
3、是变量作用域的问题,有时候循环里的变量想要用到循环外,则必须在循环外面定义
5、在做加法的时候,有两个注意点
每做完一行全部的运算,要给num数组进行清空
做进位运算时,除了完成本位的运算,还要继续进位值和其他位的运算
6、输出的时候,记录上一次操作的length是不对的,可以逆序遍历数组,寻找第一个不是0的数字并记录位置,再正向输出。 */
7、import java.io.;
**import java.util.;**//util 后面要有.
public class Summary{
public static void main (String[] args)
throws FileNotFoundException
{ Scanner input = new Scanner(new File (“sum.txt”)); PrintStream output = new PrintStream(new File(“sumout.txt”));
//用output 作为对这个程序的输出流
int[] num = new int[30]; //存放每一个数
int total=0;
while (input.hasNextLine()){
String text=input.nextLine(); //取一新的行,存入 text 这个字符串中
Scanner scan = new Scanner(text);//用scan 作为对这个行进行操作的扫描器
String t=scan.next();
int result;
output.print(t); //打印每一个数
int ll=t.length(); // ll是个数。
for (int i=0;i
num[i]=(int)c-48; //将字符转换成对应的数 }
result=ll-1; //对第一个数的处理
while (scan.hasNext())
{ String token=scan.next();
output.print(“+”+token);
deal(token,num);
//对读入的每一个“整数”进行处理,存入num数组中}
output.print(“=”);
print(num,output);
output.println();
total=total+1; }
output.println();
output.println(“The total line is “+total);
}
public static void deal(String token,int[] num) //对每一个“数”处理
{int length;
char ch;
int a;
int j;//用于记录最后的数组的元素个数,便于输出
int sum=0;//是相同位上的数的相加的和
int add=0;//是两数相加的进位数
length=token.length();//是字符串的长度,便于从字符串到数字的转换
//注意,length的长度是比真正地长度多一位
for ( int i=0;i
a=(int)ch-48;
sum=a+num[i]+add;
num[i]=sum%10;
add=sum/10; }
int k=0;
while (add>0) **
//这个循环实际上是对最后的进位进行处理。前面的for循环完成的当前数的相加,
//但是可能最高位加完以后,还是需要一步步进位到num数组的最高。只有add=0时,停止
{ sum=add+num[length+k];
num[length+k]=sum%10;
add=sum/10;
k++; } }
public static void print(int[] num,PrintStream output)
//打印最后结果的一个函数
{int local=0;
for (int i=29;i>=0;i—{
if (num[i]!=0) {
local=i;
break;//找到第一个不为0的数就记录位置并退出循环} }
for (int j=local;j>=0;j—) {
output.print(num[j]);
num[j]=0;} //别忘了对数组进行清空 }}
8、import java.util.;
public class TicTacToe {
public static final int SIZE = 3;
public static final int ROWS = 8;
public static void main(String[] args) {
System.out.println(“Let’s play tic tac toe”);
System.out.println();
Scanner console = new Scanner(System.in);
do { char[][] board = initializeBoard();
int moves = 0;
boolean userTurn = yesTo(“Do you want to go first?”, console);
boolean done = false;
while (!done && moves < SIZE SIZE) {
moves++;
if (userTurn) {
doUserMove(console, board);
} else { done = doComputerMove(board); }
userTurn = !userTurn;
printBoard(board); }
if (moves == SIZE * SIZE) {
System.out.println(“Cat’s game”); }
System.out.println(); }
while (yesTo(“Want to play again?”, console)); }
public static char[][] initializeBoard() {
char[][] result = new char[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
result[i][j] = ‘ ‘; } }
return result; }
public static void doUserMove(Scanner console, char[][] board) {<br /> boolean good = false;<br /> int row = -1;<br /> int col = -1;<br /> while (!good) {<br /> System.out.print("Your move? ");<br /> row = console.nextInt() - 1;<br /> col = console.nextInt() - 1;<br /> if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {<br /> System.out.println("Numbers must be between 1 and " + SIZE); } else if (board[row][col] != ' ') {<br /> System.out.println("That square is already taken");} <br />else { good = true; } }<br /> board[row][col] = 'X'; }
public static int valueOf(char[] row) {<br /> int userCount = 0;<br /> int myCount = 0;<br /> for (int i = 0; i < SIZE; i++) {<br /> if (row[i] == 'X') {<br /> userCount++; } <br />else if (row[i] == 'O') {myCount++;}}<br />if (userCount > 0 && myCount > 0) { return 0; // mixed row} <br />if (userCount == SIZE - 1) { return 2; // user 2-in-a-row} <br />else if (myCount == SIZE - 1) {return 3; // computer 2-in-a-row} <br />else if (userCount == SIZE) {return 4; // user 3-in-a-row} <br />else {return 1;}}<br />public static boolean doComputerMove(char[][] board) {<br /> int maxPriority = 0;<br /> char[] temp = new char[SIZE];<br /> int free = -1;<br /> int bestRow = -1;<br />int bestCol = -1;<br />for (int i = 0; i < ROWS; i++) {<br /> // copy row into temp and remember the last 'free' square<br />for (int j = 0; j < SIZE; j++) { if (i < 3) { temp[j] = board[i][j]; } <br />else if (i < 6) {temp[j] = board[j][i - SIZE];} <br />else if (i == 6) { temp[j] = board[j][j]; } <br />else { temp[j] = board[j][SIZE - 1 - j]; }<br />if (temp[j] == ' ') {free = j; }}<br /> int priority = valueOf(temp);<br /> if (priority > maxPriority) {<br /> // remember this priority and the square to move to<br />maxPriority = priority;<br />if (i < 3) { bestRow = i; } <br />else { bestRow = free;}<br /> if (i < 3 || i == 6) {bestCol = free; } <br />else if (i < 6) { bestCol = i - SIZE; } <br />else {bestCol = SIZE + 1 - free; }}}<br />if (maxPriority >= 1 && maxPriority <= 3) {<br />System.out.println("I move to " + (bestRow + 1) + ", " + (bestCol + 1));<br /> board[bestRow][bestCol] = 'O'; }<br />if (maxPriority == 0) { // cats game<br /> return true;} <br />else if (maxPriority == 3) {System.out.println("I win");<br /> return true; } <br />else if (maxPriority == 4) {System.out.println("You win");<br /> return true; } <br />else { return false; } }
public static void drawLine() {
for (int i = 0; i <= 4 * SIZE; i++) {System.out.print(“-“);}
System.out.println();}
public static void printBoard(char[][] board) {
drawLine();
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {System.out.print(“| “ + board[i][j] + “ “);}
System.out.println(“|”);
drawLine();}
System.out.println();}
// asks the user a yes/no question, returns true if yes<br /> public static boolean yesTo(String prompt, Scanner console) {<br /> System.out.print(prompt + " ");<br /> String response = console.next().toLowerCase();<br /> while (!response.equals("y") && !response.equals("n")) {<br /> System.out.println("Please answer y or n.");<br /> System.out.print(prompt + " ");<br /> response = console.next().toLowerCase();}<br /> return response.equals("y"); }}<br />这是下棋的一条题目,重点是其中的算法问题,这个需要注意,并且再读懂备注。
类的使用
这是一个类,关于一系列分数的操作
public class RationalNumber
{ int numerator;//分子
int denominator;//分母
//这是类里域的一个定义
public RationalNumber(int numerator1,int denominator2) {
if (denominator2==0) System.out.println(“Wrong!”);
numerator=numerator1;
denominator=denominator2; }
//与类名相同的第一个方法是这个类的构造器
public RationalNumber(){
this(0,1); } this**关键字的用法需要注意
//另一个构造器,及不给定参数的构造器
public int getNumerator(){
return numerator; }
public boolean equals(RationalNumber other) {
if (numerator/denominator==other.numerator/other.denominator)
return true;
else return false;}
public RationalNumber add(RationalNumber other) {
int k=0;
int x,y;
x=0; y=0;
x = numeratorother.denominator; //通分第一个分子
y = denominatorother.numerator; //通分第二个分子
y=y+x; //实现两个分子的相加 所以现在的y是最后的分子
x=other.denominator*denominator; //现在的x是最后的分母 //辗转相除找最大公约数,实现对分母的约分
int a,b; a=x; b=y;
do{ k=a%b; a=b; b=k; }while (k!=0);
x=x/a; y=y/a;
return new RationalNumber(y,x); }
public RationalNumber sub(RationalNumber other) {
int k=0; int x,y; x=0;y=0;
x = numeratorother.denominator; //通分第一个分子
y = denominatorother.numerator; //通分第二个分子
y=x-y; //y现在是最后的分子
x=other.denominatordenominator; //x现在是最后的分母
int a,b; a=x; b=y;
do{k=a%b; a=b; b=k; }while (k!=0);
x=x/a; y=y/a;
return new RationalNumber(y,x);}
public String toString(RationalNumber p) {
String s;
if (p.numerator%p.denominator==0) {
int x=p.numerator/p.denominator;
s=String.valueOf(x); }
else s=String.valueOf(p.numerator)+’/‘+String.valueOf(p.denominator);
//也可以写成 return “”+numerator 表示前面输出一个空的字符串
return s; }}
这是关于分数的那个主函数
import java.io.;
import java.util.*;//用于Scanner类的时候需要有这句话
//问题就是关于字符和数字的转换,相差48,这个一定要记住
//还有就是关于字符串,不能直接像数组那样直接表示,要用 charAt()表示!**
public class RationalNumberMain
{ public static void main (String[] args)
{ Scanner console = new Scanner(System.in);
int x1=0; int x2=0; int x3=0; int x4=0;
System.out.println(“Please input the 1 RationalNumber with the format a/b “);
String Line1 = console.next();//以字符串的形式读入一个数
x1=(int)Line1.charAt(0)-48;
x2=(int)Line1.charAt(2)-48;
System.out.println(“Please input the operation you want to do(+ -)”);
String ans = console.next();
char ch=ans.charAt(0);
System.out.println(“Please input the 2 RationalNumber with the format a/b”);
String Line2 = console.next();
x3=(int)Line2.charAt(0)-48;
x4=(int)Line2.charAt(2)-48;
RationalNumber r1 = new RationalNumber(x1,x2);
RationalNumber r2 = new RationalNumber(x3,x4);
if (ch==’+’) {
RationalNumber r3 = new RationalNumber();
r3=r1.add(r2); //注意在调用类的时候,前面要写的是定义的参数的名字,而不是类的,名字
String s=r3.toString(r3);
System.out.println(“The answer is”+s); }
if (ch==’-‘)
{ RationalNumber r4 = new RationalNumber();
r4=r1.sub(r2);
String s1=r4.toString(r4); }
System.out.println(“The answer is “+s1); }}
对于一个分数的操作,只能在这个分数内进行
如:两个数相加,只能在一个分数的类的方法里传递另一个分数,从而实现两个数的相加。
则带来的问题就是,做相减操作时,被减数和减数就有了一定的区别,需要注意!
并且,一定要将相加相减的结果给一个新的分数类型的变量,防止出现一些指针指错的情况,使得答案出现问题。
继承与接口
public class Employee{
public int getHours()
{ return 40; }
public double getSalary()
{ return 40000.0; }
public int getVactionDays()
{return 10;}
public String getVacationForm()
{return “yellow”; }}
这是一个接口
public class Janitor extends Employee{
public int getHours()
{return 2*super.getHours();}
//注意一下super关键字的用法
public double getSalary()
{return super.getSalary()-10000.0; }
public int getVactionDays()
{return super.getVactionDays()/2;}
public String clean()
{return “Workin’ for the man.”; }}
这是一个对接口的继承
super.getHour()表示对父类方法的一个引用
主函数
public class EmployeeMain{
public static void main(String[] args)
{
System.out.println(“Employee:HarvardLawyer”);
Employee HarvardLawyer = new Employee();
System.out.println(“workinghours:”+HarvardLawyer.getHours()+’,’);
System.out.printf(“Salary $%.2f, “,HarvardLawyer.getSalary());
System.out.println();
System.out.println(“VactionDays:”+HarvardLawyer.getVactionDays()+’,’);
System.out.println(“VacationForm:”+HarvardLawyer.getVacationForm());
System.out.println();<br />System.out.println("Employee:Janitor");<br /> Employee Janitor = new Employee();<br /> System.out.println("workinghours:"+Janitor.getHours()+',');<br /> System.out.printf("Salary $%.2f, ",Janitor.getSalary());<br /> System.out.println();<br /> System.out.println("VactionDays:"+Janitor.getVactionDays()+',');<br /> System.out.println("VacationForm:"+Janitor.getVacationForm());<br /> }<br />}
顶层接口:计算表面积和体积
public interface Shape3D{
public double volume();
public double SuperFicial();}
1、直接用一个类实现接口
import java.lang.;*//Math类所在包
public class SquarePyramid implements Shape3D
{ private double a,h,l;
public SquarePyramid(double a,double h)//是一个类,所以有构造器
{ this.a=a; //this关键字表示和作用域一样的名字,以示区分
this.h=h; }
public double volume()
{ double V=1.0/3(aa)*h;//1/3的值为零,所以要写成1.0/3.
return V; }
public double SuperFicial()
{ l=Math.sqrt(1/2aa+hh);**
double s1=al(1/2);
double S=s14+a*a;
return S;}}
- 用一个抽象类实现接口,再用继承的方法依次实现
public abstract class CircularShape implements Shape3D{
//当用abstract修饰类时,此类就是抽象类,抽象类不能生成对象,
//它必须被继承。
//当abstract修饰方法时,此方法为抽象方法;
//该方法不用去实现,留给子类去实现使用;
//有抽象方法的类一定是抽象类,抽象类不一定有抽象方法;
//abstract不能和final ,static 同时使用会报错!
//抽象类里可以不实现接口里的方法。 接口继承接口,类实现接口
private double R;
public CircularShape(double R)** //构造方法
{ this.R=R; }
public double getR()
{ return R; } //返回R的方法
public double getS()//底座的面积
{ return Math.PIRR; } } //返回底座面积的方法
public abstract class CircularShapeWithHeight extends CircularShape{
//对上面抽象类的一个继承
private double height;
public CircularShapeWithHeight(double R,double height)
{ super(R); //用上面抽象类里的构造器构造一个半径
this.height=height; }
public double getheight()
{ return height; } } //多了一个返回高度的方法
//对上面的父类的一个继承,是一个子类
public class CircularCone extends CircularShapeWithHeight//这是圆锥
{ private double R,height;
public CircularCone(double R,double height)
{ super(R,height); } //是上面CircularShapeWithHeight类里的构造方法
public double volume()
{ R=getR(); //getR是 CircularShape的方法
height=getheight(); //getheight 是 CircularShapeWithHeight的方法
double V=Math.PIRRheight(1.0/3);
return V; }
public double SuperFicial()
{double C=2Math.PIR;
double s1=Cheight;
double s2=Math.PIRR;
double S=s1+2s2;
return S; } }
在最终的子类里,实现了顶层接口里的两个方法**
- 关于长方体和正方体里的计算关系
public class RectangularPrism implements Shape3D
{ private double width,height,length;
public RectangularPrism(double width,double height,double length)
{ this.width=width;
this.height=height;
this.length=length; }
public double volume()
{ double V=widthheightlength;
return V; }
public double SuperFicial()
{ double s1=widthlength;
double s2=lengthheight;
double s3=heightwidth;
double S=(s1+s2+s3)2;
return S;} }
正方体是一个对上面长方体计算的继承
public class Cube extends RectangularPrism
{ private double width,height,length;
public Cube(double a)
{ super(a,a,a);**//则表示为将a赋值给长方体里的长宽高。} }
//直接改变构造器,就可以全部用父类里的方法**
ArrayList
1、对文件的每一行,每一行的每一个单词,逆序
import java.util.;
import java.io.;
public class converse{
public static void main(String[] args)
throws FileNotFoundException
{ Scanner input = new Scanner(new File(“ReverseFileTest.txt.txt”));
restore(input); }
public static void restore(Scanner f)
{ ArrayList
while (f.hasNextLine())
{ String Line=f.nextLine();
Scanner scan = new Scanner(Line);
while (scan.hasNext()) results.add(scan.next());** 添加方法
results.add(“enter”); } //每一行做一个标记,打印时提醒换行
Write(results);}
public static void Write(ArrayList
{ int q=results.size(); q=q-1;
while (q>=0)
{ if(!results.get(q).equals(“enter”))
//q虽然是内存,但是它在循环里表示的是下标。
{ System.out.print(results.get(q));
System.out.print(“ “);}
else System.out.println(); q—; } } }
2、找两个文件里的重叠部分
import java.util.;
import java.io.;//这个是有Scanner要用的包
public class Overlap{
public static void main(String[] args)
throws FileNotFoundException
{ System.out.println(“Please input the names of which you want to compare:”);
System.out.println(“1:”);
Scanner console=new Scanner(System.in);
String file1=console.nextLine();
System.out.println(“2:”);
String file2=console.nextLine();
Scanner input1=new Scanner(new File(file1));
Scanner input2=new Scanner(new File(file2));
ArrayList
ArrayList
ArrayList
AnswerWrite(overlap,list1,list2); }
public static ArrayList
{ input.useDelimiter(“[^a-zA-Z’]+”);
ArrayList
while (input.hasNext())
{ String s=input.next();
s.toLowerCase(); **//将s转换成全部的小写模式
words.add(s); } //读入每一个单词并加入到words中
Collections.sort(words); //对words进行字母顺序地排序
ArrayList
if (words.size()>0)
{ results.add(words.get(0));
for (int i=1;i
else results.add(words.get(i)); } }
return results; }//
public static ArrayList
getOverlap(ArrayList
{ ArrayList
int index1,index2; index1=0; index2=0;
while (index1
if (comparison==0)
{ results.add(list1.get(index1)); index1++; index2++; }
else if (comparison<0) index1++; else index2++;}
//list1里的单词比较小,所以预防list1后面会出现和list2中一样的
//因此应该是index1往后移
return results; }
public static void AnswerWrite(ArrayList
{ System.out.println(“file1 #1 words=”+l1.size());
System.out.println(“file2 #2 words=”+l2.size());
System.out.println(“common words=”+overlap.size());
double per1=overlap.size()100.0/l1.size();
double per2=overlap.size()100.0/l2.size();
System.out.println(“% of file1 in overlap =” +per1);
System.out.println(“% of file2 in overlap =” +per2); }}
- 最重要的族谱程序
设计一个Person类,能存放自身名字和父母子女的信息。父母分别是一个Person类的引用,子女信息存放到一个ArrayList中
设计一个FamilyInfo类,用来存放所有的家族成员。该类能通过族谱文件建立遗传关系
保存族谱信息的文件分为两部分,前半部分是所有成员的姓名,后半部分是血缘关系
import java.io.;
import java.util.;
public class Person
{ Person father; Person mother; String name; ArrayList
public Person(String name1)//**类的一个构造器
{ name=name1; father=null; mother=null; kids= new ArrayList
//对一个新建Person类的初始化
public String getName()
{ return name; }
public Person getFather()
{ return father; }
public Person getMother()
{ return mother; }
public void setMother(Person mother1)
{ mother=mother1; }
public void setFather(Person father1)
{father=father1; }
public void addKids(Person kid1)
{ kids.add(kid1); }
public int numKids() public Person nthKid(int i)
{ int num=kids.size(); return num; } { return kids.get(i); } }
//这个程序是用来处理那些血缘关系。
//FamilyInfo是一个类,这个类其中的一个field是一个ArrayList,且这个ArrayList的名字叫做 people。
//里面存放的类型都是Person类的。
import java.io.;
import java.util.;
{ ArrayList
public FamilyInfo()//构造器,就是对类里的field初始化。
{ people = new ArrayList
public void read(Scanner input)
//是将所有人的名字都生成一个Person,并存入ArrayList中。
{ for (;;) { String personName = input.nextLine();
if (personName.equals(“END”)) { break; }
Person current=new Person(personName);
people.add(current); }
ProcessParents(input); }
public int getNumbers()//用来获取这个家族的总人数。
{ int n=people.size(); return n; }
public Person getPerson(int i)
//用来依次获取每个人的姓名,与目标姓名做比较。
{ Person p=people.get(i);//获得姓名是用的Person类里的方法。
return p; }
public void ProcessParents(Scanner input)
//实际上是处理那个文件的后半段,即将所有人的关系存进去。
{ String personName,motherName,fatherName;
Person person,mother,father;
for(;;){ personName = input.nextLine();
if (personName.equals(“END”)) { break; }
person= getPerson(personName);
motherName = input.nextLine();
fatherName = input.nextLine();
mother = getPerson(motherName);//不应该是new一个新的Person,而是应该在ArrayList里找到相对应的然后建立联系
person.setMother(mother);
mother.addKids(person); }
if (!fatherName.equals(“unknown”))
{ father = getPerson(fatherName);
person.setFather(father);
father.addKids(person); } } }
public Person getPerson(String name)
{ int pos=indexOf(name);//获得指定名字的人的下标
if(pos!=-1){ return people.get(pos);}
//应该是返回ArrayList里的Person,而不是new一个新的person,否则process后的信息就表现不出来了
else { return null; }}
public int indexOf(String name)//寻找指定姓名的人的下标
{for(int i=0;i
return -1;
} }
import java.io.;
import java.util.;
{ public static void main(String[] args)
throws FileNotFoundException{
System.out.println(“Please input the Familyinfo’s name you want to search in:”);
Scanner console = new Scanner(System.in);
String file=console.nextLine(); //file是文件名;
FamilyInfo family=new FamilyInfo();
Scanner input = new Scanner(new File(file));
family.read(input);
System.out.print(“Please input the person’s name you want to search:”);
String name=console.nextLine();
Person person = new Person(name);
Search(name,family); }
public static void Search(String currentname,FamilyInfo family)
{ Person next=family.getPerson(currentname);
if(next==null){ System.out.println(“no match.”); }
else { showMother(next);
showFather(next);
showChildren(next); }}
public static void showMother(Person own)
{ System.out.println(“Mather Line:”);
int level = 1;
while (own !=null)
{ for (int i=0;i<=level;i++)
{ System.out.print(“ “); }
System.out.println(own.getName());
own=own.getMother();
level++;}
System.out.println(); }
public static void showFather(Person own)
{与上面一样}
public static void showChildren(Person own)
{ System.out.println(“Children:”);
if (own.numKids()==0)
{ System.out.println(“ none”); }
else { for (int i=0;i
System.out.println();}} }
Collection
Collection版本的单词overlap
import java.io.;
import java.util.;
public class Vocabulary
{ public static void main(String[] args)
throws FileNotFoundException
{ Scanner console = new Scanner(System.in);
System.out.println(“file1 #1 name?”);
Scanner input1 = new Scanner(new File(console.nextLine()));
System.out.println(“file2 #2 name?”);
Scanner input2 = new Scanner(new File(console.nextLine()));
System.out.println();
Set
Set
Set
overlap.retainAll(sets2);
reportResults(sets1,sets2,overlap); }
public static Set
{ input.useDelimiter(“[^a-zA-Z’]+”);**// 正则表达式**
Set
while (input.hasNext())
{
String next = input.next().toLowerCase();
words.add(next); }
return words; }
public static void reportResults(Set
{ System.out.println(“file #1 words = “ + sets1.size());
System.out.println(“file #2 words = “ + sets2.size());
System.out.println(“common words = “ + overlap.size());
double pct1 = 100.0*overlap.size()/sets1.size();<br /> double pct2 = 100.0*overlap.size()/sets2.size();
System.out.println("% of file 1 in overlap = " + pct1);<br /> System.out.println("% of file 2 in overlap = " + pct2);<br /> } }<br />**因为collection本身的性质决定了它其中不可能含有相同的元素,因而可以直接省去去掉相同元素的方法**
找单词距离
import java.io.;
import java.util.;
public class EditDistance {
public static void main(String[] args)
throws FileNotFoundException {
giveIntro();
Scanner console = new Scanner(System.in);
System.out.println(“What is the dictionary file? “);
String fileName = console.nextLine();
Scanner dictionary = new Scanner(new File(fileName));
System.out.println();
Map
doMatches(console, neighbors); }
public static boolean isNeighbor(String s1, String s2)
//邻居:是指只有一个字母不一样的两个单词
{if (s1.length() != s2.length())
{ return false; }
else //s1和s2长度相等的情况下
{ int count = 0;
for (int i = 0; i < s1.length(); i++)
{ if (s1.charAt(i) != s2.charAt(i))
{ count++;
if (count > 1)
//不一样字母的数量超过一个,就返回false
{return false; } } } return (count == 1);}}
public static Map
//key是字符串 value是一个列表
{Map
//新建一个Map
while (dictionary.hasNext()) {
result.put(dictionary.next(), new ArrayList
//给每一个新获得的单词都找到自己的neighbour,即长度一样的单词。
for (String s : result.keySet())
//返回此映射中包含的键的 Set 视图
//将map中所有的键存入到Set集合,因为set具备迭代器,所有迭代方式取出所有的键
//再根据get()方法 ,获取每一个键对应的值
//双重循环是一个一个的找,即遍历两次。
{ for (String other : result.keySet())
{ if (isNeighbor(s, other))
//如果other是s的邻居,则将other放入s关键词对应的value里,即添加到ArrayList中
{ result.get(s).add(other);}} }return result; }
public static void showPath(String word1, String word2, Map
//path地图是用来记录路径
{ String current = word2;
String result = current;
while (!current.equals(word1)) {
current = path.get(current); result = current + “, “ + result; }
System.out.println(result); }
public static int editDistance(String word1, String word2, Map
//计算距离的核心算法
//在最后一个方法里用到了 word1是输入单词,word2是目标单词
{ LinkedList
//LinkedList 是一个双链表,在添加和删除元素时具有比ArrayList更好的性能.但在get与set方面弱于ArrayList.
//当然,这些对比都是指数据量很大或者操作很频繁的情况下的对比。
//它还实现了 Queue 接口,该接口比List提供了更多的方法,包括 offer(),peek(),poll()等.
Set
Map
//explored是一个集合
//path是显示路径的一个map,key是 value是
candidates.add(word1);
int distance = 0;
int numNeighbors = 1;
int nextNumNeighbors = 0;
int count = 0;
while (!candidates.isEmpty()) {
String next = candidates.removeFirst();//这个方法返回此列表的第一个元素
if (next.equals(word2)) //找到了目标单词
{showPath(word1, word2, path);
return distance;}
else //没有找到的情况
{ explored.add(next);
for (String s : neighbors.get(next)) {
if (!explored.contains(s)) {
explored.add(s);
candidates.add(s);
path.put(s, next);
nextNumNeighbors++; }}
count++;
if (count == numNeighbors) { // last neighbor at this distance
distance++;
numNeighbors = nextNumNeighbors;
nextNumNeighbors = 0;
count = 0; } }}
return -1; }
public static void doMatches(Scanner console, Map
//domatch方法 用来获取两个字符
{ for (;;) {System.out.println(“Let’s find an edit distance between words.”);
System.out.print(“ first word (enter to quit)? “);
String word1 = console.nextLine().trim();
if (word1.length() == 0) { break; }
else if (!neighbors.containsKey(word1))
{System.out.println(word1 + “ is not in the dictionary”); }
//判断单词是否在单词表里
else { System.out.print(“ second word? “);
String word2 = console.nextLine().trim();
if (!neighbors.containsKey(word2)) {
System.out.println(word2 + “ is not in the dictionary”);}
else //开始正式操作,即两个单词均在单词表里
{ int distance = editDistance(word1, word2, neighbors);
//editDistance方法是用来计算距离的
if (distance == -1) { System.out.println(“No solution”); }
else { System.out.println(“Edit distance = “ + distance); }}}
System.out.println(); } } }
递归算法:
import java.util.;
import java.io.;
public class Sequence{
public static void main(String[] args)
{ Scanner console = new Scanner (System.in);
System.out.println(“Please input the length of the array you want to creat:”);
int n=console.nextInt();
writeSequence(n); }
public static void writeSequence(int n)
{ if (n<1) { throw new IllegalArgumentException();}
else if (n==1) {System.out.print(1);}
else if (n==2) {System.out.print(“1 1”);}
else {
int number = (n+1)/2;
System.out.print(number+ “ “); //打印一头一尾
writeSequence(n-2); //在对中间的数字段进行操作
System.out.print(“ “+number);
}}}
这条程序主要是注意那个递归公式,即理解它的含义
奇数和偶数的最简单情况便是公式里的base
然后每次传递的参数实际上是中间字段的长度,而头尾的数字恰好是中间字段长度的一般。因为有了递归
归并排序+字符数组+不区分大小写
import java.io.;
import java.util.;
public class SortNames {
public static void main (String[] args) throws FileNotFoundException
{ Scanner console = new Scanner(System.in);
System.out.println(“What is the input file?”);
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
System.out.println();
String[] names = readNames(input);
mergeSort(names);
for (String s:names){ System.out.println(s);} }
public static String[] readNames(Scanner input)
{ List
while (input.hasNextLine()){ data.add(input.nextLine());}
String[] result = new String[data.size()];
data.toArray(result);
return result; }
public static void swap(String[] a,int i, int j)
{if(i!=j){ String temp = a[i]; a[i] = a[j]; a[j] = temp;}}
public static void mergeSort(String[] array)
{if (array.length>1){
int size1 = array.length / 2;
int size2 = array.length - size1;
String[] half1 = new String[size1]String[] half2 = new String[size2];
for (int i = 0;i
public static void merge(String[] result,String[] list1,String[] list2){
int i1=0; int i2=0; for (int i = 0;i
{ result[i] = list1[i1]; i1++; }
else{ result[i] = list2[i2]; i2++;} } } }
这条程序的重点是在字符数组和ArrayList的转换
因为ArrayList没有subList的功能,subList实现的是一个List接口,是相当于ArrayList的一个父类,因此是不能将一个List赋值给ArrayList的
栈和队列
import java.io.;
import java.util.;
public class splitStack
{public static void main(String[] args){
Stack
Stack
Stack
Scanner console = new Scanner(System.in);
System.out.println(“Please input the numbers:”);
String num = console.nextLine();
Scanner token = new Scanner(num);
while (token.hasNext())
{ String s = token.next();
Int n = Integer.parseInt(s); **//这是一个将字符串转换成整数的方法。
before.push(n); }
int l=before.size();
System.out.println(“initial stack is:”+before);
for (int i=0;i
int l1=negative.size();
for (int i=0;i
for (int i=0;i
import java.io.;
import java.util.*;
public class compressDuplicate{
public static void main(String[] args){
Stack
Stack
Scanner console = new Scanner(System.in);
System.out.println(“Please input the numbers:”);
String num = console.nextLine();
Scanner token = new Scanner(num);
int n;
while (token.hasNext())
{ String s = token.next();
n = Integer.parseInt(s);
initial.push(n); }
System.out.println(“intial stack is:”+initial);
int last=initial.pop(); int l=initial.size(); int count=1;
for (int i=0;i
else{ after.push(last); after.push(count); last=current; count=1;}}
after.push(last); after.push(count); int l1=after.size();
for (int i=0;i
System.out.println(“after change:”+initial);}}
import java.io.;
import java.util.;
public class doubleDigits{
public static void main(String[] args)
{ Scanner console = new Scanner(System.in);
int n = console.nextInt();
int result=0;
if (n==0) System.out.println(n);//对于n为负数的处理
if (n<0) { n=0-n;
result=doubleDigits(n);
System.out.println(“-“+result); }
else { result=doubleDigits(n);
System.out.println(result); } }
public static int doubleDigits(int n)
{int a,b; // a表示每一个数除最后一位的所有,b表示最后一位数
if (n/10==0)
{ return (n10+n);//就是对每一个单独的数字进行double }
else { a=n/10; b=n%10;
b=b10+b; //给最末尾的数字double
a=doubleDigits(a); //a是给前面的数求双
return (a*100+b); //每一个求完双的a都要给末尾的两位数留下位置
} }}
import java.io.;
import java.util.;
public class writeBinary{
public static void main(String[] args)
{ Scanner console = new Scanner(System.in);
int n= console.nextInt();
writeBinary(n); }
public static void writeBinary(int n)
{if (n==0||n==1) System.out.print(n);
//0和1是二进制的基本形式,所以作为递归的base
else { writeBinary(n/2); //相当于短除法里的商,不断地被除2
System.out.print(n%2); //相当于从最后一个商为0的余数开始,倒着往上一层写 } } }
import java.io.;
import java.util.;
public class countBinary{
public static void main(String[] args)
{ Scanner console = new Scanner(System.in);
int n = console.nextInt();
if (n==0) System.out.println();
else countBinary(n); }
public static void countBinary(int n)
{ //在这个循环里,i表示2的i次方
int a=1;
for (int i=0;i
for (int i=0;i
for (int j=a/2;j //从2的i-1次方到2的i次方-1,因为不同的i要不不同数目的0
{for (int b=0;b
writeBinary(j); //递归打印二进制
System.out.println();
} } }
import java.io.;
import java.util.;
public class Hanoi{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println(“Please input the numbers of the disks you want to move:”);
int disknum = console.nextInt();
movement(disknum,’A’,’B’,’C’); }
public static void movement(int n,char from,char pass,char to)
{if (n==1)
{ System.out.println(“disk “+n+” move form “+from+” to “+to);}
else { movement(n-1,from,to,pass);
System.out.println(“disk “+n+” move form “+from+” to “+to);
movement(n-1,pass,from,to); } } }