长整型求和
import java.io.;
import java.util.;
public class sum {
public static final int DIGITS = 25;
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File(“files/sum.txt”));
processFile(input);
}
public static void processFile(Scanner input) {
int lines = 0;
while(input.hasNextLine()) {
String text = input.nextLine();
Scanner data = new Scanner(text);
processLine(data);
lines++;
}
}
public static void processLine(Scanner data) {
int[] result = new int[DIGITS];
String next = data.next();
transfer(next, result);
System.out.print(next);
while(data.hasNext()) {
next = data.next();
int[] number = new int[DIGITS];
transfer(next, number);
addTo(result, number);
System.out.print(“ + “ + next);
}
System.out.print(“ = “);
print(result);
System.out.println();
}
public static void transfer(String data, int[] digits) {
int i = data.length() - 1;
int j = DIGITS - 1;
while(i >= 0) {
digits[j] = Character.getNumericValue(data.charAt(i));
i—;
j—;
}
}
public static void addTo(int[] sum, int[] number) {
int carry = 0;
for(int i = DIGITS - 1 ; i >= 0 ; i—) {
int next = sum[i] + number[i] + carry;
sum[i] = next % 10;
carry = next / 10;
}
if(carry > 0)
throw new RuntimeException(“overflow”);
}
public static void print(int[] digits) {
int start = 0;
while(start < DIGITS - 1 && digits[start] == 0) {
start++;
}
for(int i = start ; i < DIGITS ; i++) {
System.out.print(digits[i]);
}
}
}
分数类
public class RationalNumber {
//fields
private int numerator;
private int denominator;
//constructors
public RationalNumber(int numerator, int denominator) {
if(denominator == 0)
throw new IllegalArgumentException(“Wrong Denominator : 0”);
this.numerator = numerator;
this.denominator = denominator;
}
public RationalNumber() {
this.numerator = 0;
this.denominator = 1;
//this(0,1)
}
//methods
public int getNumerator() {
return numerator;
}
public RationalNumber add(RationalNumber other) {
int newNumerator = numerator other.getDenominator() + denominator other.getNumerator();
int newDenominator = denominator other.getDenominator();
RationalNumber result = new RationalNumber(newNumerator, newDenominator);
return reduce(result);
}
private static RationalNumber reduce(RationalNumber a) {
int symbol = 1;
boolean sym = a.getDenominator() > 0 && a.getNumerator() < 0 || a.getDenominator() < 0 && a.getNumerator() > 0;
if(sym) {
symbol = -1;
}
RationalNumber c = new RationalNumber(Math.abs(a.getNumerator()) , Math.abs(a.getDenominator()));
int smaller = c.getDenominator() > c.getNumerator() ? c.getNumerator() : c.getDenominator();
int max = 1;
for(int i = 1 ; i <= smaller ; i++) {
if(c.getDenominator() % i == 0 && c.getNumerator() % i == 0)
max = i;
}
RationalNumber b = new RationalNumber(c.getNumerator() / max symbol , c.getDenominator() / max);
return b;
}
public String toString() {
if(denominator == 1)
return numerator + “”;
else {
RationalNumber a = new RationalNumber(this.getNumerator(),this.getDenominator());;
RationalNumber b = reduce(a);
if(b.getDenominator() == 1)
return b.getNumerator() + “”;
else
return b.getNumerator() + “/“ + b.getDenominator();
}
}
}
public interface Shape3D {
public double volume();
public double superficialArea();
}
public abstract class CircularShape implements Shape3D{
private double r;
public CircularShape(double r) {
this.r = r;
}
public double getR() {
return r;
}
public double area() {
return r r Math.PI;
}
}
public abstract class CircularShapeWithHeight extends CircularShape{
private double h;
public CircularShapeWithHeight(double r , double h) {
super(r);
this.h = h;
}
public double getH() {
return h;
}
}
public class CircularCone extends CircularShapeWithHeight{
public CircularCone (double r , double h) {
super(r,h);
}
public double volume() {
return area() getH() / 3.0;
}
public double superficialArea() {
return 2.0 area() + getH() Math.PI 2.0 getR();
}
}
import java.io.;
import java.util.;
public class Reverse {
public static void main(String[] args)
throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println(“Please enter the file: “);
String name = console.nextLine();
Scanner input = new Scanner(new File(name));
ArrayList
while(input.hasNextLine()) {
lines.add(input.nextLine());
}
for(int i = lines.size() - 1 ; i >= 0 ; i—) {
print(lines.get(i));
}
}
public static void print(String s) {
ArrayList
Scanner input = new Scanner(s);
while(input.hasNext()) {
words.add(input.next());
}
if(words.size() > 0) {
System.out.print(words.get(words.size() - 1));
for(int i = words.size() - 2 ; i >= 0 ; i—) {
System.out.print(“ “ + words.get(i));
}
}
System.out.println();
}
}
import java.util.
public class FamilyInfo {
private ArrayList
private final String LIST_END = “END”;
public FamilyInfo() {
people = new ArrayList
}
public Person getPerson(String name) {
int pos = indexOf(name);
if(pos != -1) {
return people.get(pos);
} else {
return null;
}
}
private int indexOf(String name) {
for(int i = 0 ; i < people.size() ; i++) {
if(people.get(i).getName().equalsIgnoreCase(name)) {
return i;
}
}
return -1;
}
public void read(Scanner input) {
String name = input.nextLine();
while(!name.contentEquals(LIST_END)) {
people.add(new Person(name));
name = input.nextLine();
}
ProcessParents(input);
}
private void ProcessParents(Scanner input) {
String personName , motherName , fatherName;
Person person , mother , father;
for(;;) {
personName = input.nextLine();
if(personName.equals(LIST_END)) {
break;
}
person = getPerson(personName);
motherName = input.nextLine();
fatherName = input.nextLine();
if(!motherName.contentEquals(“unknown”)) {
mother = getPerson(motherName);
person.setMother(mother);
mother.addKid(person);
}
if(!fatherName.contentEquals(“unknown”)) {
father = getPerson(fatherName);
person.setFather(father);
father.addKid(person);
}
}
}
}
import java.util.;
public class Person {
private String name;
private Person mother;
private Person father;
private ArrayList
public Person(String person) {
name = person;
mother = null;
father = null;
kids = new ArrayList
}
public String getName() {
return name;
}
public Person getMother() {
return mother;
}
public Person getFather() {
return father;
}
public int numKids() {
return kids.size();
}
public Person nthKid(int n) {
return kids.get(n);
}
public void setMother(Person mother) {
this.mother = mother;
}
public void setFather(Person father) {
this.father = father;
}
public void addKid(Person kid) {
kids.add(kid);
}
}
import java.io.
import java.util.;
*public class FamilyTest
{ 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();}} }
package javatest08;
import java.util.;
import java.io.;
public class Vocabulary {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println(“file1 name?”);
Scanner input1 = new Scanner(new File(console.nextLine()));
System.out.println(“file2 name?”);
Scanner input2 = new Scanner(new File(console.nextLine()));
System.out.println();
Set
Set
Set
overlap.retainAll(set2);
reportResults(set1 , set2 , 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(“file1 words = “ + set1.size());
System.out.println(“file2 words = “ + set2.size());
System.out.println(“common words = “ + overlap.size());
if(set1.size() > 0 && set2.size() > 0) {
double percent1 = 100.0 overlap.size() / set1.size();
double percent2 = 100.0 overlap.size() / set2.size();
System.out.println(“% of file1 in overlap = “ + percent1);
System.out.println(“% of file2 in overlap = “ + percent2);
} else
System.out.println(“There is no common word between file1 and file2”);
}
}
package javatest09;
import java.util.;
public class WriteSequenceBetterEdition {
public static void main(String[] args) {
Scanner console = new Scanner(System.**_in);
System.out.println(“Please enter a number n(n>1):”);
int a = console.nextInt();
writeSequence(a);
}
public static void writeSequence(int n) {
if(n < 1)
throw new IllegalArgumentException(“Illegal n : “ + n);
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);
}
}
}
package test;
import** java.util.;
public class Sieve {
public static void main(String[] args) {
System.out.println(“This program will tell you all prime\n” +
“numbers up to a given maximum.”);
System.out.println();
Scanner console = new Scanner(System.in);
System.out.print(“Maximum?”);
int max = console.nextInt();
long timeBeforeRun = System.currentTimeMillis();
LinkedList
long timeAfterRun = System.currentTimeMillis();
System.out.println(“The method costs: “ + (timeBeforeRun - timeAfterRun) + “ milliseconds”);
System.out.println(“Prime numbers up to “ + max + “:”);
System.out.println(primes);
}
public static LinkedList
LinkedList
LinkedList
for(int i = 2 ; i <= max ; i++) {
numbers.add(i);
}
while(!numbers.isEmpty()) {
int front = numbers.remove(0);
primes.add(front);
Iterator
while(itr.hasNext()) {
int current = itr.next();
if(current % front == 0) {
itr.remove();
}
}
}
return primes;
}
public static LinkedList
LinkedList
LinkedList
numbers.add(2);
for(int i = 3 ; i <= max ; i+=2) {
numbers.add(i);
}
while(!numbers.isEmpty()) {
int front = numbers.remove(0);
primes.add(front);
if(front > Math._sqrt
primes.addAll(numbers);
return primes;
}
Iterator
while(itr.hasNext()) {
int current = itr.next();
if(current % front == 0) {
itr.remove();
}
}
}
return primes;
}
}
package test;
import java.util.;
public class Sieve {
public static void main(String[] args) {
System.out.println(“This program will tell you all prime\n” +
“numbers up to a given maximum.”);
System.out.println();
Scanner console = new Scanner(System.in);
System.out.print(“Maximum?”);
int max = console.nextInt();
long timeBeforeRun = System.currentTimeMillis();
LinkedList
long timeAfterRun = System.currentTimeMillis();
System.out.println(“The method costs: “ + (timeBeforeRun - timeAfterRun) + “ milliseconds”);
System.out.println(“Prime numbers up to “ + max + “:”);
System.out.println(primes);
}
public static LinkedList
LinkedList
LinkedList
numbers.add(2);
for(int i = 3 ; i <= max ; i+=2) {
numbers.add(i);
}
while(!numbers.isEmpty()) {
int front = numbers.remove(0);
primes.add(front);
if(front > Math._sqrt
primes.addAll(numbers);
return primes;
}
Iterator
while(itr.hasNext()) {
int current = itr.next();
if(current % front == 0) {
itr.remove();
}
}
}
return primes;
}
}
找单词距离
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); }