yvsou.com  · web viewcreate a sentence by selecting a word at random from each array in the...

17

Click here to load reader

Upload: hoangtruc

Post on 14-Apr-2018

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

Experiment 3Strings and Java IO

1, Objectives1) 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

create sentences. Use four arrays of strings called article, noun, verb and preposition.

Create a sentence by 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 start with 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 noun array should contain the nouns "boy", "girl", "dog", "town" and

"car"; the verb array should contain the verbs "drove", "jumped", "ran", "walked"

and "skipped"; the preposition array should contain the prepositions "to", "from",

"before", "over", "under" and "on".

Codes:

package randomsen;

import java.util.Random;

public class randomse

{

Page 2: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

public static void 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","form","before","over","under","on"};

for(int i=0;i<20;i++)

{

Random rand = new Random();

int num1 = rand.nextInt(6);

String string1=article[num1];

int num2 = rand.nextInt(5);

String string2=noun[num2];

int num3 = rand.nextInt(5);

String string3=verb[num3];

int num4 = rand.nextInt(6);

String string4=preposition[num4];

int num5 = rand.nextInt(6);

String string5=article[num5];

int num6 = rand.nextInt(5);

String string6=noun[num6];

StringBuilder randomsen=new StringBuilder(10);

randomsen.insert(0, ".");

randomsen.insert(0, string6);

randomsen.insert(0, " ");

randomsen.insert(0, string5);

randomsen.insert(0, " ");

randomsen.insert(0, string4);

Page 3: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

randomsen.insert(0, " ");

randomsen.insert(0, string3);

randomsen.insert(0, " ");

randomsen.insert(0, string2);

randomsen.insert(0, " ");

string1 = string1.substring(0, 1).toUpperCase() + string1.substring(1);

randomsen.insert(0, string1);

randomsen.insert(0, " ");

System.out.println(randomsen.toString());

}

}

}

Output:

Page 4: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

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.

Codes:

package listfiles;

import java.io.File;

import java.io.ObjectInputStream.GetField;

public class listf

{

public static void main(String[] args)

{

File f=new File("/Users/liaomengchun/Desktop/井盖图片/破损");

String[] files = f.list();

for(int i=0;i<files.length;i++)

{

File f1=new File("/Users/liaomengchun/Desktop/井盖图片/破损/"+files[i]);

if(f1.isDirectory())

{

System.out.println("Floder:"+f1);

}

else

{

long n=f1.length();

if(n<1024)

{

System.out.println(f1+" "+n+"B");

}

Page 5: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

else if(n<1048576)

{

System.out.println(f1+" "+n/1024+"K");

}

else if(n<1073741824)

{

System.out.println(f1+" "+n/1048576+"M");

}

else

{

System.out.println(f1+" "+n/1073741824+"G");

}

}

}

}

}

Output:

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

Page 6: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

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. )

Codes:package RacerRecord;

import java.io.*;import java.util.NoSuchElementException;import java.util.Scanner;

public class ReadRacerFile { private FileInputStream input; InputStreamReader read; File file = null;

// enable user to select file to open public void openFile() throws UnsupportedEncodingException, FileNotFoundException {

file = new File("C:\\Users\\John\\IdeaProjects\\racers.txt"); input = new FileInputStream(file); read = new InputStreamReader(input, "GBK"); }// end method openFile

//read record from file

public void readRecords() throws IOException { BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { System.out.println(lineTxt); } }

public void closeFile() throws IOException { if (input != null) input.close(); }

Page 7: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

}package RacerRecord;

import java.io.IOException;

public class ReadRacerFileTest { public static void main(String[] args) throws IOException { ReadRacerFile application=new ReadRacerFile();

application.openFile(); application.readRecords(); application.closeFile(); }}

4) See Exam 17.8

Use this array:

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

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

Page 8: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

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

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

Codes:package TelephoneNumberWordGenerator;

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) { // We have hit the end of the input phone number and thus the end of // recursion allResults.add(resultSoFar); } else { // Strip the next character off the front of the phone number Character nextDigit = Character.valueOf(input.charAt(0));

Page 9: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

// Look up the list of mappings from that digit to all letters char[] mappingArray = digitMap.get(nextDigit);

// More robust error handling would throw an exception or do // something else when an unknown character was encountered in the // phone number. if (mappingArray != null) {

// We have processed the first digit in the rest of the number, // so recurse with the rest of the number String inputTail = input.substring(1);

// By iterating through the array the mapping lists do not all // have to be the same size. 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(); // 文件夹的创建 创建文件夹\OUTPUT } 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(); } }

Page 10: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and

/** * 最简单的文件读写方法是使用类 FileWriter * (它的父类依次是 java.io.OutputStreamWriter——>java.io.Writer——>java.lang.Object ); */

// 向文件 file2 里面写数据 try { FileWriter fileWriter = new FileWriter(file2); for (String nextResult : string) { fileWriter.write(nextResult+"\t"); }

fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block 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>();

// Starting condition is that the entire input needs to be processed, // the result so far is empty, and we have nothing in the list of final // answers convert(num, "", results); WriteFile(results); System.out.println("End of results list. Total words generated: " + results.size()); }}

Page 11: yvsou.com  · Web viewCreate a sentence by selecting a word at random from each array in the following ... C. Compute the winning percentage of every racer and store the name and