练习2:
// Repair InfiniteRecursion.java
import java.util.*;
public class Ja13_3_2 {
public String toString() {
return " InfiniteRecursion address: " + super.toString() + "\n";
}
public static void main(String[] args) {
List v =
new ArrayList();
for(int i = 0; i < 10; i++)
v.add(new Ja13_3_2());
System.out.println(v);
}
}
练习3:
// Modify Turtle.java so that it sends all output to System.err.
import java.io.*;
import java.util.*;
public class Ja13_5_3{
private String name;
private Formatter f;
public Ja13_5_3(String name, Formatter f) {
this.name = name;
this.f = f;
}
public void move(int x, int y) {
f.format("%s The Ja13_5_3 is at (%d,%d)\n", name, x, y);
}
public static void main(String[] args) {
PrintStream outAlias = System.err;
Ja13_5_3 tommy = new Ja13_5_3("Tommy",
new Formatter(System.out));
Ja13_5_3 terry = new Ja13_5_3("Terry",
new Formatter(outAlias));
tommy.move(0,0);
terry.move(4,8);
tommy.move(3,4);
terry.move(2,5);
tommy.move(3,3);
terry.move(3,3);
}
}
练习4:
/* Modify Ja13_5_4.java so that the widths are all controlled by a single
* set of constant values. The goal is to allow you to easily change a width
* by changing a single value in one place.
*/
import java.util.*;
public class Ja13_5_4 {
private double total = 0;
private Formatter f = new Formatter(System.out);
private int i=20;
private String s1="%-"+i+"s %5s %10s\n";
private String s2="%-"+i+".15s %5d %10.2f\n";
private String s3="%-"+i+"s %5s %10.2f\n";
public void printTitle() {
f.format(s1, "Item", "Qty", "Price");
f.format(s1, "----", "---", "-----");
}
public void print(String name, int qty, double price) {
f.format(s2, name, qty, price);
total += price;
}
public void printTotal() {
f.format(s3, "Tax", "", total*0.06);
f.format("%-15s %5s %10s\n", "", "", "-----");
f.format(s3, "Total", "",
total * 1.06);
}
public static void main(String[] args) {
Ja13_5_4 receipt = new Ja13_5_4();
receipt.printTitle();
receipt.print("Jack's Magic Beans", 4, 4.25);
receipt.print("Princess Peas", 3, 5.1);
receipt.print("Three Bears Porridge", 1, 14.29);
receipt.printTotal();
}
}
练习5:
/* For each of the basic conversion types in the above table, write the
* most complex formatting expression possible. That is, use all the possible
* format specifiers available for that conversion type.
*/
import java.math.*;
import java.util.*;
class Conversion{}
public class Ja13_5_5 {
public static void main(String[] args) {
Formatter f = new Formatter(System.out);
char u = 'a';
System.out.println("char u = \'a\'");
f.format("%-2s%-2S%-2c%-2C%-5b%-5B%-3h%-3H%%\n", u,u,u,u,u,u,u,u);
int v = 121;
System.out.println("int v = 121");
f.format("%-4s%-4S%-4d%-4c%-4C%-5b%-5B%-4x%-4X%-4h%-4H%%\n", v,v,v,v,v,v,v,v,v,v,v);
BigInteger w = new BigInteger("50000000000000");
System.out.println("BigInteger w = 50000000000000");
f.format("%-15s%-15S%-5b%-5B%-15x%-15X%-5h%-5H%%\n", w,w,w,w,w,w,w,w);
double x = 179.543;
System.out.println("double x = 179.543");
f.format("%-8s%-8S%-5b%-5B%-15f%-15e%-15E%-12h%-12H%%\n", x,x,x,x,x,x,x,x,x);
Conversion y = new Conversion();
System.out.println("Conversion y = new Conversion()");
f.format("%-20s%-20S%-5b%-5B%-10h%-10H%%\n", y,y,y,y,y,y);
boolean z = false;
System.out.println("boolean z = false");
f.format("%-7s%-7S%-7b%-7B%-7h%-7H%%\n", z,z,z,z,z,z);
}
}
/*char u = 'a'
a A a A true TRUE 61 61 %
int v = 121
121 121 121 y Y true TRUE 79 79 79 79 %
BigInteger w = 50000000000000
50000000000000 50000000000000 true TRUE 2d79883d2000 2D79883D2000 8842a1a788
42A1A7%
double x = 179.543
179.543 179.543 true TRUE 179.543000 1.795430e+02 1.795430E+02 1ef462c
1EF462C %
Conversion y = new Conversion()
Conversion@75ad44f6 CONVERSION@75AD44F6 true TRUE 75ad44f6 75AD44F6 %
boolean z = false
false FALSE false FALSE 4d5 4D5 %*/
练习6:
/* Create a class that contains int, long, float, and double fields. Create
* a toString() method for this class that uses String.format(), and demonstrate
* that your class works correctly.
*/
import java.util.*;
import static net.mindview.util.Print.*;
class A{
private int i;
private float f;
private long l;
private double d;
A(int i,float f,long l,double d){
this.i=i;this.f=f;this.l=l;this.d=d;
}
public String toString(){
return String.format("%5d,%5.5f,%5d,%5.10g",i,f,l,d);
}
}
public class Ja13_5_6{
public static void main(String[] args){
A a=new A(5,5.55f,10000l,8.666666e01);
System.out.println(a);
}
}
//g表示double,long也用d表示
练习7:
/* Using the documentation for java.util.regex.Pattern as a resource,
* write and test a regular expression that checks a sentence to see
* that it begins with a captial letter and ends with a period.
*/
import static net.mindview.util.Print.*;
public class Ja13_6_7{
public static void main(String[] agrs){
String s="Using the documentation for java.util.regex.Pattern.";
print(s.matches("^[A-Z].*\\."));
}
}
练习8:
// Split the string Splitting.knights on the words "the" or "you."
import static net.mindview.util.Print.*;
import java.util.*;
public class Ja13_6_8{
public static void main(String[] agrs){
String s="Then, when you have found the shrubbery, you must " +
"cut down the mightiest tree in the forest... " +
"with... a herring!";
print(Arrays.toString(s.split("the|you")));
}
}
练习9:
// Using the documentation for java.util.regex.Pattern as a resource,
// replace all the vowels in Splitting.knights with underscores.
import static net.mindview.util.Print.*;
import java.util.*;
public class Ja13_6_9{
public static void main(String[] agrs){
String s="Then, when you have found the shrubbery, you must " +
"cut down the mightiest tree in the forest... " +
"with... a herring!";
print(s.replaceAll("a|o|e|i|u","_"));
}
}
练习10:
/* For the phrase "Java now has regular expressions" evaluate whether the following
* expressions will find a match:
* ^Java
* \Berg.*
* n.w\s+h(a|i)s
* S?
* S+
* s{4}
* s{1}.
* s{0,3}
*/
import java.util.regex.*;
import static net.mindview.util.Print.*;
public class Ja13_6_10{
public static void main(String[] args){
String s[]={"^Java","\\Berg.*","n.w\\s+h(a|i)s","S?","S+","s{4}","s{1}.","s{0,3}"};
String ss="Java now has regular expressions";
for(String regex:s){
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(ss);
while(m.find())print(regex+": "+m.group());
}
}
}
练习11:
/* Apply the regular expression:
* (?i)((^[aeiou])|(\s+[aeiou]))\W+?[aeiou]\b
* to
* "Arline ate eight apples and one orange while Anita hadn't any"
*/
import java.util.regex.*;
import static net.mindview.util.Print.*;
public class Ja13_6_11{
public static void main(String[] args){
Pattern p=Pattern.compile("(?i)((^[aeiou])|(\\s+[aeiou]))\\W+?[aeiou]\\b");
Matcher m=p.matcher("Arline ate eight apples and one orange while Anita hadn't any");
if(m.find())print(m.group());
else print("no");
}
}
练习12:
/* Modify Groups.java to count all of the unique words that do not start with a
* capital letter.
*/
import java.util.*;
import java.util.regex.*;
import static net.mindview.util.Print.*;
public class Ja13_6_12{
static public final String POEM =
"Twas brillig, and the slithy toves\n" +
"Did gyre and gimble in the wabe.\n" +
"All mimsy were the borogoves,\n" +
"And the mome raths outgrabe.\n\n" +
"Beware the Jabberwock, my son,\n" +
"The jaws that bite, the claws that catch.\n" +
"Beware the Jubjub bird, and shun\n" +
"The frumious Bandersnatch.";
public static void main(String[] args){
Matcher m=Pattern.compile("(?m)(^|\\s+)([a-z]\\w+)").matcher(POEM);
//Matcher m=Pattern.compile("((^[a-z])|\\s+)([a-z]\\w+)").matcher(POEM);
int i=0;
Set set=new LinkedHashSet();
while(m.find()){
set.add(m.group().trim());
}
print(set.size());
print(set);
}
}
//(?m)((^|\\W+)([^A-Z]\\w+)\\W+)+ //前后空格会挤掉后一个单词
//(?m)(^|\\W+)([^A-Z]\\w+) // \\W+会把逗号也牵扯进来
//((^[a-z])|\\s+)([a-z]\\w+)
//
练习13:
// Modify StartEnd.java so that it uses Groups.POEM as input, but still produces positive
// outputs for find(), lookingAt() and matches().
import java.util.regex.*;
import static net.mindview.util.Print.*;
import static strings.Groups.*;
public class Ja13_13{
public static String input =
"As long as there is injustice, whenever a\n" +
"Targathian baby cries out, wherever a distress\n" +
"signal sounds among the stars ... We'll be there.\n" +
"This fine ship, and this fine crew ...\n" +
"Never give up! Never surrender!";
private static class Display {
private boolean regexPrinted = false;
private String regex;
Display(String regex) { this.regex = regex; }
void display(String message) {
if(!regexPrinted) {
print(regex);
regexPrinted = true;
}
print(message);
}
}
static void examine(String s, String regex) {
Display d = new Display(regex);
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find())
d.display("find() '" + m.group() +
"' start = "+ m.start() + " end = " + m.end());
if(m.lookingAt()) // No reset() necessary
d.display("lookingAt() start = "
+ m.start() + " end = " + m.end());
if(m.matches()) // No reset() necessary
d.display("matches() start = "
+ m.start() + " end = " + m.end());
}
public static void main(String[] args) {
for(String in : POEM.split("\n")) {
print("input : " + in);
for(String regex : new String[]{"\\w*ere\\w*",
"\\w*ever", "T\\w+", "Did.*"})
examine(in, regex);
}
}
}
练习14:
// Rewrite SplitDemo using String.split().
import java.util.regex.*;
import java.util.*;
import static net.mindview.util.Print.*;
public class Ja13_14{
public static void main(String[] args){
String input =
"This!!unusual use!!of exclamation!!points";
print(Arrays.toString(
input.split("!!")));
// Only do the first three:
print(Arrays.toString(
input.split("!!", 3)));
}
}
练习15:
// Modify JGrep.java to accept flags as arguments (e.g., Pattern.CASE_INSENSITIVE,
// Pattern.MULTILINE).
// {Args: JGrep15.java "\b[Ssct]\w+", Pattern.CASE_INSENSITIVE}
import java.util.regex.*;
import net.mindview.util.*;
public class Ja13_15{
public static void main(String[] args){
if(args.length < 2) {
System.out.println("Usage: java JGrep file regex");
System.exit(0);
}
Pattern p = Pattern.compile(args[1],Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
// Iterate through the lines of the input file:
int index = 0;
Matcher m = p.matcher("");
for(String line : new TextFile(args[0])) {
m.reset(line);
while(m.find())
System.out.println(index++ + ": " +
m.group() + ": " + m.start());
}
}
}
练习16:
/* Modify JGrep.java to accept a directory name or a file name as argument
* (if a directory is provided, search should include all files in the
* directory). Hint: You can generated a list of file names with:
* File[] files = new File(".").listFiles();
*/
import java.util.regex.*;
import net.mindview.util.*;
import java.io.*;
import static net.mindview.util.Print.*;
public class Ja13_16{
public static void main(String[] args){
/*if(args.length < 2) {
System.out.println("Usage: java JGrep file regex");
System.exit(0);
}*/
Pattern p = Pattern.compile("IMPORT.*;",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);
// Iterate through the lines of the input file:
int index = 0;
Matcher m = p.matcher("");
File[] files = new File("C:\\Thinking_In_Java\\abc").listFiles();
for(File file:files){
for(String line : new TextFile(file.getName())) {
m.reset(line);
while(m.find())
System.out.println(index++ + ": " +
m.group() + ": " + m.start());
}
}
}
}
练习17:
/* Write a program that reads a Java source-code file (you provide the
* file name on the command line) and displays all the comments.
*/
import java.util.regex.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class Ja13_17{
public static void main(String[] args){
String ar="Ja13_16.java";
Matcher m=Pattern.compile("(/\\*(.*)\\*/)|(.*(//.*$))",Pattern.DOTALL|Pattern.MULTILINE).matcher("");
for(String line:new TextFile(ar)){
m.reset(line);
while(m.find()){print(m.group(1)+"\n"+m.group(4));}
}
}
}
//无法获取多行/**/注释??
练习18:
/* Write a program that reads a Java source-code file (you provide the
* file name on the command line) and displays all the string literals
* in the code.
*/
import java.util.regex.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class Ja13_18{
public static void main(String[] args){
String ar="Ja13_16.java";
Matcher m=Pattern.compile("(\\w+)\\W+",Pattern.DOTALL|Pattern.MULTILINE).matcher("");
for(String line:new TextFile(ar)){
m.reset(line);
while(m.find()){print(m.group(1));}
}
}
}
练习19:
/* Building on the previous two exercises, write a program that examines
* Java source-code and produces all the class names used in a particular
* program.
*/
import java.util.regex.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
public class Ja13_19{
public static void main(String[] args){
String ar="Ja13_16.java";
Matcher m=Pattern.compile("class (\\w+)\\W+",Pattern.DOTALL|Pattern.MULTILINE).matcher("");
for(String line:new TextFile(ar)){
m.reset(line);
while(m.find()){print(m.group(1));}
}
}
}
练习20:
/* Create a class that contains int, long, float and double and String fields.
* Create a constructor for this class that takes a single String argument, and
* scans that string into the various fields. Add a toString(0 method and
* demonstrate that your class works correctly.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import java.io.*;
public class Ja13_20{
public static void main(String[] args){
String s="5 57673 4.5787 9.3557 dasfdsv";
Scanner sc=new Scanner(new BufferedReader(new StringReader(s)));
int i=sc.nextInt();
long l=sc.nextLong();
float f=sc.nextFloat();
double d=sc.nextDouble();
String ss=sc.next();
print(" i "+i+" l: "+l+" f: "+f+" "+" d: "+d+" ss: "+ss);
}
}