Experiment 3

Strings and Java IO

1, Objectives

1)String and StringBuilder

2)Java IO

3)Collections

2, Contents

(Copy the results or source codes after each exercise. Rename this document as “Id – Name.doc” and hand in it onto yvsou.com. )

1) (Random Sentences) Write an application that uses random-number generation to createsentences. Use four arrays of strings called article, noun, verb and preposition. Create a sentenceby selecting a word at random from each array in the following order: article, noun, verb, preposition,article and noun. As each word is picked, concatenate it to the previous words in the sentence.The words should be separated by spaces. When the final sentence is output, it should startwith a capital letter and end with a period. The application should generate and display 20 sentences.

The article array should contain the articles "the", "a", "one", "some", "every"and "any"; the nounarray should contain the nouns "boy", "girl", "dog", "town" and "car"; the verb array should containthe verbs "drove", "jumped", "ran", "walked" and "skipped"; the preposition array shouldcontain the prepositions "to", "from","before", "over", "under" and "on".

import java.util.Random;

publicclass main_1 {

publicstaticvoid main(String args[]){

String article[] = {"the ", "a ", "one ", "some ", "every " , "any "};

String noun[] = {"boy ", "girl ", "dog ", "town " , "car "};

String verb[] = {"drove ", "jumped ", "ran ", "walked " , "skipped "};

String preposition[] = {"to.", "from.", "before.", "over.", "under." , "on."};

Random rd = new Random();

for(inti = 0;i<20;i++){

StringBuilder builder = new StringBuilder();

intnumber1 = rd.nextInt(article.length);

builder.append(article[number1]);

intnumber2 = rd.nextInt(noun.length);

builder.append(noun[number2]);

intnumber3 = rd.nextInt(verb.length);

builder.append(verb[number3]);

intnumber4 = rd.nextInt(preposition.length);

builder.append(preposition[number4]);

System.out.println(builder);

}

}

}

2) List all the directories and files. Make a mark when showing directory. Display the file size after file name with three digits, for example, 123B, 123K, 123M, and so on.

package package_1;

import java.io.File;

publicclass main_2 {

publicstaticvoid main(String args[]){

File f = new File("D:/");

String[] files = f.list();

for(String str: files){

File a = new File("D:/"+str);

if(a.isDirectory()){

System.out.println("invalid");

}

else

{

if(a.length()<1024)

System.out.println(str+" "+a.length()+"B");

if(a.length()>1024 & a.length()<1024*1024)

System.out.println(str+" "+a.length()/1024+"K");

if(a.length()>1024*1024)

System.out.println(str+" "+a.length()/1024/1024+"M");

}

}

}

}

3) Some objects of Racer class are stored in file “racers.data”.

A. Read the Racer objects from “racers.data”.

B. Find all the Brazil racers and print summary of wins.

C. Compute the winning percentage of every racer and store the name and the percentage in a file. [Hints: winning percentage = wins / starts ]

( Class Recer and file “racers.data” are presented along with this file. )

package package_3;

import java.io.*;

import java.util.*;

publicclass main_3 {

publicstaticvoid main(String[] args){

List<Racer> racers = new ArrayList<Racer>();

try{

ObjectInputStream ois = new ObjectInputStream(

new FileInputStream("C:\\Users\\Administrator\\workspace\\Experiment_3\\src\\package_3\\racers.txt"));

Object obj = null;

while((obj = ois.readObject())!=null){

racers.isEmpty();

}

ois.close();

}

catch(IOException e){

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

写到这发现文件不知怎么回事就是打不开,出现一堆错误,像下面这样,就写不下去了…..

java.lang.ClassNotFoundException: ex3.Racer

at java.net.URLClassLoader.findClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Unknown Source)

at java.io.ObjectInputStream.resolveClass(Unknown Source)

at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)

at java.io.ObjectInputStream.readClassDesc(Unknown Source)

at java.io.ObjectInputStream.readArray(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.defaultReadFields(Unknown Source)

at java.io.ObjectInputStream.readSerialData(Unknown Source)

at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)

at java.io.ObjectInputStream.readObject0(Unknown Source)

at java.io.ObjectInputStream.readObject(Unknown Source)

at package_3.main_3.main(main_3.java:13)

4) See Exam 17.8

Use this array:

private static final String[][] letters = { { " ", " ", " " },

{ " ", " ", " " }, { "A", "B", "C" }, { "D", "E", "F" },

{ "G", "H", "I" }, { "J", "K", "L" }, { "M", "N", "O" },

{ "P", "R", "S" }, { "T", "U", "V" }, { "W", "X", "Y" } };

package main_5;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class WordGenerator {
private static Map<Character, char[]> digitMap;
static {
digitMap = new HashMap<Character, char[]>();
digitMap.put(Character.valueOf('0'), new char[]{' '});
digitMap.put(Character.valueOf('1'), new char[]{' '});
digitMap.put(Character.valueOf('2'), new char[]{'A', 'B', 'C'});
digitMap.put(Character.valueOf('3'), new char[]{'D', 'E', 'F'});
digitMap.put(Character.valueOf('4'), new char[]{'G', 'H', 'I'});
digitMap.put(Character.valueOf('5'), new char[]{'J', 'K', 'L'});
digitMap.put(Character.valueOf('6'), new char[]{'M', 'N', 'O'});
digitMap.put(Character.valueOf('7'), new char[]{'P', 'R', 'S'});
digitMap.put(Character.valueOf('8'), new char[]{'T', 'U', 'V'});
digitMap.put(Character.valueOf('9'), new char[]{'W', 'X', 'Y'});
}
public static void convert(String input, String resultSoFar, List<String> allResults) {
if (input.length() == 0) {
allResults.add(resultSoFar);
} else {
Character nextDigit = Character.valueOf(input.charAt(0));
char[] mappingArray = digitMap.get(nextDigit);
if (mappingArray != null) {
String inputTail = input.substring(1);
for (char nextLetter : mappingArray) {
// Put the next mapped letter on the end of the result being
// built and recurse
convert(inputTail, resultSoFar + nextLetter, allResults);
}
}
}
}
public static void WriteFile(List<String> string){
File file1 = new File("\\OUTPUT");
if (file1.exists()) {
System.out.println("存在文件夹a");
} else {
file1.mkdir();

}
File file2 = new File("\\OUTPUT\\WordsResult.txt");
if (file2.exists()) {
System.out.println("存在WordsResult.txt");
System.out.println(file2.getAbsolutePath());
} else {
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
FileWriter fileWriter = new FileWriter(file2);
for (String nextResult : string) {
fileWriter.write(nextResult+"\t");
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// ask for phone number
Scanner in=new Scanner(System.in);
System.out.println("Enter a telephone number: (7 digits)");
String num = in.nextLine();
List<String> results = new ArrayList<String>();
convert(num, "", results);
WriteFile(results);
System.out.println("End of results list. Total words generated: " + results.size());
}
}