chapter 6

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

in fourteen-hundred 92 columbus sailed the ocean blue :) Given these lines of input, what tokens does a <code>Scanner</code> break the line apart into?

"in", "fourteen-hundred", "92", "columbus", "sailed", "the", "ocean", "blue", ":)"

Answer the following questions about a Java program located on a Linux machine in the folder /home/amanda/Documents/hw6 : What are the legal ways you can refer to the file /home/amanda/Documents/hw6/names.txt? /home/amanda/Documents/hw6/data/numbers.txt? /home/amanda/download/saved.html?

"names.txt" "/home/amanda/Documents/hw6/names.txt" "data/numbers.txt" "/home/amanda/Documents/hw6/data/numbers.txt" "/home/amanda/download/saved.html"

Answer the following questions about a Java program located on a Windows machine in the folder C:\Users\amanda\Documents\programs : a. What are the legal ways you can refer to the file C:\Users\amanda\Documents\programs\numbers.dat? C:\Users\amanda\Documents\programs\data\homework6\input.dat? C:\Users\amanda\Documents\homework\data.txt?

"numbers.dat" "C:/Users/amanda/Documents/programs/numbers.dat" "C:/Users/amanda/Documents/programs/data/homework6/input.dat" "data/homework6/input.dat" "C:/Users/amanda/Documents/homework/data.txt"

welcome...to the matrix. Given this line of input, what tokens does a <code>Scanner</code> break the line apart into?

"welcome...to", "the", "matrix."

Consider a file called readme.txt that has the following contents: 6.7 This file has several input lines. 10 20 30 40 test What would be the output from the code in the previous exercise (shown below) if the calls to hasNext and next were replaced by calls to hasNextInt and nextInt, respectively? How about hasNextDouble and nextDouble ? Scanner input = new Scanner(new File("readme.txt")); int count = 0; while (input.hasNext()) { System.out.println("input: " + input.next()); count++; } System.out.println(count + " total"); hasNextInt/nextInt hasNextDouble/nextDouble

0 total input: 6.7 1 total

What type of object is used to write output to a file in Java? What methods does the above object have available for you to use?

PrintStream print println printf

Write code to print the following four lines of text into a file named message.txt, in the same directory as your program. Notice that the third line is blank. Testing, 1, 2, 3. This is my output file.

PrintStream out = new PrintStream(new File("message.txt")); out.println("Testing,"); out.println("1, 2, 3."); out.println(); out.println("This is my output file.");

Change the following code to be correct: (Hint: If you can't figure it out, try pasting the code into your text editor and printing the String in this line of code.) Scanner input = new Scanner(new File("C:\temp\new files\test.dat"));

Scanner input = new Scanner(new File("C:/temp/new files/test.dat"));

Which of the following is the correct syntax to declare a <code>Scanner</code> to read the file <code>example.txt</code> in the current directory?

Scanner input = new Scanner(new File("example.txt"));

Change the following code to be correct: Scanner input = new Scanner("test.dat");

Scanner input = new Scanner(new File("test.dat"));

Write a statement that constructs a Scanner object, stored in a variable named input, to read the file input.txt, which exists in the same folder as your program.

Scanner input=new Scanner(new File("input.txt"));

How can we read data from a file in Java?

Using a Scanner in conjunction with a File object.

Consider a file called readme.txt that has the following contents: 6.7 This file has several input lines. 10 20 30 40 test What would be the output from the code in the previous exercise if the calls to hasNextLine and nextLine were replaced by calls to hasNext and next, respectively, as shown below? Scanner input = new Scanner(new File("readme.txt")); int count = 0; while (input.hasNext()) { System.out.println("input: " + input.next()); count++; } System.out.println(count + " total"); output

input: 6.7 input: This input: file input: has input: several input: input input: lines. input: 10 input: 20 input: 30 input: 40 input: test 12 total

Consider a file called readme.txt that has the following contents: 6.7 This file has several input lines. 10 20 30 40 test What would be the output from the following code when it is run on the readme.txt file? Scanner input = new Scanner(new File("readme.txt")); int count = 0; while (input.hasNextLine()) { System.out.println("input: " + input.nextLine()); count++; } System.out.println(count + " total"); output

input: 6.7 This file has input: several input lines. input: input: 10 20 30 40 input: input: test 6 total

Write a method named readEntireFile that accepts a Scanner representing an input file as its parameter, then reads that file and returns the entire text contents of that file as a String.

public String readEntireFile(Scanner in) { String content =""; while (in.hasNextLine()) { content += in.nextLine(); content += "\n"; } return content; }

Write a method named negativeSum that accepts a Scanner as a parameter reading input from a file containing a series of integers, and determine whether the sum starting from the first number is ever negative. The method should print a message indicating whether a negative sum is possible and should return true if a negative sum can be reached and false if not. For example, if the file contains the following text, your method will consider the sum of just one number (38), the sum of the first two numbers (38 + 4), the sum of the first three numbers (38 + 4 + 19), and so on up to the sum of all of the numbers: 38 4 19 -27 -15 -3 4 19 38 None of these sums is negative, so the method would produce the following message and return false: no negative sum If the file instead contains the following numbers, the method finds that a negative sum of -8 is reached after adding 6 numbers together (14 + 7 + -10 + 9 + -18 + -10): 14 7 -10 9 -18 -10 17 42 98 It should output the following and return true, indicating that a negative sum can be reached: -8 after 6 steps

public boolean negativeSum(Scanner in) { int step =0; int sum = 0; boolean flag = false; while (in.hasNextInt()) { sum+= in.nextInt(); step++; if (sum < 0) { flag = true; break; } } if (flag) { System.out.println(sum + " after " + step + " steps"); } else { System.out.println("no negative sum"); } return flag; }

The following program contains 6 errors. Correct the errors and submit a working version of the program. The corrected version of the program should produce the following output: Lines: 5 Words: 21 when it is run on the following input file, example.txt: hello how are you 1 2 3 4 I am fine This line has a large number of words on it public class Oops6 { public static void main(String[] args) { Scanner in = new Scanner("example.txt"); countWords(in); } // Counts total lines and words in the input scanner. public static void countWords(Scanner input) { Scanner input = new Scanner("example.txt"); int lineCount = 0; int wordCount = 0; while (input.nextLine()) { String line = input.line(); // read one line lineCount++; while (line.next()) { // tokens in line String word = line.hasNext; wordCount++; } } System.out.println("Lines: " + lineCount); System.out.println("Words: " + wordCount); } }

public class Oops6 { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("example.txt")); countWords(in); } // Counts total lines and words in the input scanner. public static void countWords(Scanner input) { int lineCount = 0; int wordCount = 0; while (input.hasNextLine()) { String line = input.nextLine(); // read one line lineCount++; while (input.hasNext()) { // tokens in line String word=input.next(); wordCount++; } } System.out.println("Lines: " + 5); System.out.println("Words: " + 21); } }

Write a complete Java program that prints itself to the console as output. Assume that the program is stored in a file named PrintMyself.java, and make your code open the file PrintMyself.java and print its contents to the console.

public class PrintMyself{ public static void main (String args[])throws FileNotFoundException{ Scanner console=new Scanner (new File("PrintMyself.java")); while (console.hasNextLine()) { System.out.println(console.nextLine()); } } }

Write a method named getFileName that repeatedly prompts the user for a file name until the user types the name of a file that exists on the system. Once you get a good file name, return that file name as a String. Here is a sample dialogue from one call to your method, assuming that the file good.txt does exist and the others do not: Type a file name: bad.txt Type a file name: not_here.txt Type a file name: good.txt

public static String getFileName() { Scanner console = new Scanner(System.in); String filename = ""; do { System.out.print("Type a file name: "); filename = console.nextLine(); } while (!(new File(filename).exists())); return filename; }

Write a method named mostCommonNames that accepts as its parameter a Scanner for an input file whose data is a sequence of lines, where each line contains a set of first names separated by spaces. Your method should print the name that occurs the most frequently in each line of the file. The method should also return the total number of unique names that were seen in the file. You may assume that no name appears on more than one line of the file. Each line should be considered separately from the others. On a given line, some names are repeated; all occurrences of a given name will appear consecutively in the file. If two or more names occur the same number of times, print the one that appears earlier in the file. If every single name on a given line is different, every name will have 1 occurrence, so you should just print the first name in the file. For example, if the input file contains the following text: Benson Eric Eric Marty Kim Kim Kim Jenny Nancy Nancy Nancy Paul Paul Stuart Stuart Stuart Ethan Alyssa Alyssa Helene Jessica Jessica Jessica Jessica Jared Alisa Yuki Catriona Cody Coral Trent Kevin Ben Stefanie Kenneth On the first line, there is one occurrence of the name Benson, two occurrences of Eric, one occurrence of Marty, three occurrences of Kim, one of Jenny, three of Nancy, and two of Paul. Kim and Nancy appear the most times (3), and Kim appears first in the file. So for that line, your method should print that the most common is Kim. The complete output would be the following. The method would also return 23, since there are 23 unique names in the entire file. Most common: Kim Most common: Jessica Most common: Jared You may assume that there is at least one line of data in the file and that each line will contain at least one name.

public static int mostCommonNames(Scanner input){ int uniqueName=0; while(input.hasNextLine()){ String line=input.nextLine(); Scanner console=new Scanner (line); String last=console.next(); uniqueName++; String commonWord=last; int mostCommon=1; int count=1; while(console.hasNext()){ String current=console.next(); if(current.equals(last)){ count++; }else{ if(count>mostCommon){ mostCommon=count; commonWord=last; } count=1; uniqueName++; } last=current; } if(count>mostCommon){ commonWord=last; } System.out.println("Most common: "+commonWord); } return uniqueName; }

Write a method named boyGirl that accepts a Scanner as a parameter. The Scanner is reading its input from a file containing a series of names followed by integers. The names alternate between boys' names and girls' names. Your method should compute the absolute difference between the sum of the boys' integers and the sum of the girls' integers. The input could end with either a boy or girl; you may not assume that it contains an even number of names. If the input file tas.txt contains the following text: Steve 3 Sylvia 7 Craig 14 Lisa 13 Brian 4 Charlotte 9 Jordan 6 then your method could be called in the following way: Scanner input = new Scanner(new File("tas.txt")); boyGirl(input); and should produce the following output, since the boys' sum is 27 and the girls' sum is 29: 4 boys, 3 girls Difference between boys' and girls' sums: 2

public static void boyGirl(Scanner input){ int boySum=0; int girlSum=0; int boys=0; int girls=0; int count=0; while(input.hasNext()){ if(count==0){ input.next(); boys++; boySum+=input.nextInt(); count++; } else{ input.next(); girls++; girlSum+=input.nextInt(); count=0; } } System.out.println(boys + " boys, " + girls + " girls"); System.out.println("Difference between boys' and girls' sums: " + Math.abs(boySum-girlSum)); }

Write a static method named collapseSpaces that accepts a Scanner representing a file as a parameter and writes that file's text to the console, with multiple spaces or tabs reduced to single spaces between words that appear on the same line. For example, if a Scanner variable named input is reading an input file containing the following text: four score and seven years ago our fathers brought forth on this continent a new nation then the call collapseSpaces(input); should produce the following output: four score and seven years ago our fathers brought forth on this continent a new nation Each word is to appear on the same line in output as it appears in the file. Notice that lines can be blank.

public static void collapseSpaces(Scanner in) { String line, outline; Scanner line_in; while(in.hasNextLine()) { line = in.nextLine(); line_in = new Scanner(line); outline = ""; while (line_in.hasNext()) { outline += line_in.next(); outline += " "; } System.out.println(outline); } }

Write a method named doubleSpace that accepts a Scanner for an input file and a PrintStream for an output file as its parameters, writing into the output file a double-spaced version of the text in the input file. You can achieve this task by inserting a blank line between each line of output.

public static void doubleSpace(Scanner Input, PrintStream out){ while(Input.hasNextLine()){ out.println(Input.nextLine()); out.println(); } }

Write a method named inputStats that takes a Scanner representing a file as a parameter and that reports various statistics about the file's text. In particular, your method should report the number of lines in the file, the longest line, the number of tokens on each line, and the length of the longest token on each line. You may assume that the input file has at least one line of input and that each line has at least one token. For example, if a Scanner named input on file carroll.txt contains the following text: "Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch." then the call inputStats(input); should produce the following output: Line 1 has 5 tokens (longest = 11) Line 2 has 8 tokens (longest = 6) Line 3 has 6 tokens (longest = 6) Line 4 has 3 tokens (longest = 14) Longest line: the jaws that bite, the claws that catch,

public static void inputStats(Scanner input){ int lineNum=0; int longestLine=0; String longestString=""; while(input.hasNextLine()){ lineNum++; String line=input.nextLine(); if(line.length()>longestLine){ longestLine=line.length(); longestString=line; } int token=0; int longest=0; Scanner console=new Scanner (line); while(console.hasNext()){ token++; String word=console.next(); if(word.length()>longest){ longest=word.length(); } } System.out.printf("Line %d has %d tokens (longest = %d)\n", lineNum, token, longest); } System.out.println("Longest line: "+longestString); }

Write a static method named plusScores that accepts as a parameter a Scanner containing a series of lines that represent student records. Each student record takes up two lines of input. The first line has the student's name and the second line has a series of plus and minus characters. Below is a sample input: Kane, Erica --+-+ Chandler, Adam ++-+ Martin, Jake +++++++ Dillon, Amanda ++-++-+- The number of plus/minus characters will vary, but you may assume that at least one such character appears and that no other characters appear on the second line of each pair. For each student you should produce a line of output withthe student's name followed by a colon followed by the percent of plus characters. For example, if the input above is stored in a Scanner called input, the call of plusScores(input); should produce the following output: Kane, Erica: 40.0% plus Chandler, Adam: 75.0% plus Martin, Jake: 100.0% plus Dillon, Amanda: 62.5% plus

public static void plusScores(Scanner in) { while(in.hasNextLine()) { String name = in.nextLine(); String score = in.nextLine(); int n=0; int p=0; for (int i=0; i<score.length(); i++) { if(score.charAt(i) == '+') { p++; } n++; } System.out.printf("%s: %.1f%% plus\n", name, 100.0*p/n); } }

Write a method named printDuplicates that accepts as its parameter a Scanner for an input file containing a series of lines. Your method should examine each line looking for consecutive occurrences of the same token on the same line and print each duplicated token along how many times it appears consecutively. Non-repeated tokens are not printed. Repetition across multiple lines (such as if a line ends with a given token and the next line starts with the same token) is not considered in this problem. For example, if the input file contains the following text: hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge bow wow wow yippee yippee yo yippee yippee yay yay yay one fish two fish red fish blue fish It's the Muppet Show, wakka wakka wakka Your method would produce the following output for the preceding input file: how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3 wakka*3 Your code prints only the repeated tokens; the ones that only appear once in a row are not shown. Your code should place a single space between each reported duplicate token and should respect the line breaks in the original file. This is why a blank line appears in the expected output, corresponding to the fourth line of the file that did not contain any consecutively duplicated tokens. You may assume that each line of the file contains at least 1 token of input.

public static void printDuplicates (Scanner input){ while(input.hasNextLine()){ String line=input.nextLine(); Scanner console=new Scanner (line); String last=console.next(); int count=1; while(console.hasNext()){ String current=console.next(); if(last.equals(current)){ count++; }else{ if(count>1){ System.out.print(last+"*"+count+" "); } count=1; } last=current; } if(count>1){ System.out.print(last+"*"+count+" "); } System.out.println(); } }

Write a method named printEntireFile that prompts the user for a file name and prints the contents of that file to the console as output. You may assume that the file exists. For example, if the file example.txt contains the following input data: hello how are you 1 2 3 4 I am fine Then the following would be an example dialogue of your method: Type a file name: example.txt hello how are you 1 2 3 4 I am fine

public static void printEntireFile() throws FileNotFoundException { Scanner console=new Scanner (System.in); System.out.print("Type a file name: "); String user=console.next(); Scanner input= new Scanner (new File(user)); while(input.hasNext()){ System.out.println(input.nextLine()); } }

In Self-Check 6.16, you are asked to write a method named printEntireFile that prompts the user for a file name and printed that file's contents to the console. Modify your code from that problem into a new method named printEntireFile2 that will repeatedly prompt until the user types the name of a file that exists on the system. If you like, you can call the method getFileName from Self-Check 6.20 (without rewriting or pasting it here) to help you solve this problem. For example, if the file example.txt contains the following input data: hello how are you 1 2 3 4 I am fine Then the following would be an example dialogue of your method: Type a file name: bad.txt Type a file name: not_here.txt Type a file name: alsobad.txt Type a file name: example.txt hello how are you 1 2 3 4 I am fine

public static void printEntireFile2() throws FileNotFoundException { String filename = getFileName(); Scanner input = new Scanner(new File(filename)); while (input.hasNextLine()) { System.out.println(input.nextLine()); } }

Write a method called stripComments that accepts a Scanner representing an input file containing a Java program as its parameter, reads that file, and then prints the file's text with all comments removed. A comment is any text on a line from // to the end of the line, and any text between /* and */ characters. For example, consider the following text: import java.util.*; /* My program by Suzy Student */ public class Program { public static void main(String[] args) { System.out.println("Hello, world!"); // a println } public static /* Hello there */ void foo() { System.out.println("Goodbye!"); // comment here } /* */ } If the file contained this text, your program should output the following text: import java.util.*; public class Program { public static void main(String[] args) { System.out.println("Hello, world!"); } public static void foo() { System.out.println("Goodbye!"); } }

public static void stripComments(Scanner input){ while(input.hasNextLine()){ String plz=input.nextLine(); if(!plz.startsWith("/*")){ if(!plz.contains("/*")&& plz.endsWith("*/")){ plz=" "; }else if (plz.contains("/*")&& plz.contains("*/")){ plz=plz.substring(0,plz.indexOf("/*"))+plz.substring(plz.indexOf("*/")+2); }else if(plz.contains("//")){ plz=plz.substring(0,plz.indexOf("//")); } System.out.println(plz); } } }

Write a method called wordWrap that accepts a Scanner representing an input file as its parameter and outputs each line of the file to the console, word-wrapping all lines that are longer than 60 characters. For example, if a line contains 112 characters, the method should replace it with two lines: one containing the first 60 characters and another containing the final 52 characters. A line containing 217 characters should be wrapped into four lines: three of length 60 and a final line of length 37.

public static void wordWrap(Scanner Input){ String line; while(Input.hasNextLine()){ line=Input.nextLine(); while (line.length() > 60) { System.out.println(line.substring(0, 60)); line = line.substring(60); } System.out.println(line); } }

Modify the preceding wordWrap method into a new wordWrap2 method that accepts a second parameter for a PrintStream to write the data, and outputs the newly wrapped text to that PrintStream rather than to the console. Also, modify it to use a local variable to store the maximum line length rather than hard-coding 60. (You can go back to the last problem to copy your solution code from there and paste it here as a starting point.)

public static void wordWrap2(Scanner Input, PrintStream out){ String line; while(Input.hasNextLine()){ line=Input.nextLine(); while (line.length() > 60) { out.println(line.substring(0, 60)); line = line.substring(60); } out.println(line); } }

Modify the preceding wordWrap method into a new wordWrap3 method that wraps only whole words, never chopping a word in half. Assume that a word is any whitespace-separated token and that all words are under 60 characters in length. Make sure that each time you wrap a line, the subsequent wrapped line(s) each begin with a word and not with any leading whitespace. Accept only a single parameter for the input Scanner, and send your method's output to the console, as in the original wordWrap problem; do not use an output file as was done in wordWrap2.

public static void wordWrap3(Scanner input){ while(input.hasNextLine()){ String line=input.nextLine(); while(line.length()>60){ if (line.charAt(60)==' '){ System.out.println(line.substring(0,60)); line=line.substring(61); }else{ int index=line.substring(0,60).lastIndexOf(" "); System.out.println(line.substring(0,index)); line=line.substring(index+1); } } System.out.println(line); } }

Write a method named coinFlip that accepts as its parameter a Scanner for an input file. Assume that the input file data represents results of sets of coin flips that are either heads (H) or tails (T) in either upper or lower case, separated by at least one space. Your method should consider each line to be a separate set of coin flips and should output to the console the number of heads and the percentage of heads in that line, rounded to the nearest tenth. If this percentage is more than 50%, you should print a "You win" message. For example, consider the following input file: H T H H T T t t T h H h For the input above, your method should produce the following output: 3 heads (60.0%) You win! 2 heads (33.3%) 1 heads (100.0%) You win! The format of your output must exactly match that shown above. You may assume that the Scanner contains at least 1 line of input, that each line contains at least one token, and that no tokens other than h, H, t, or T will be in the lines.

public void coinFlip(Scanner in) { while (in.hasNextLine()) { Scanner line = new Scanner(in.nextLine()); int n = 0; int nh = 0; while (line.hasNext()) { String flip = line.next().toUpperCase(); if (flip.equals("H")) { nh++; } n++; } double ratio = 100.0 * nh / n; System.out.printf("%d heads (%.1f%%)\n", nh, ratio); if (ratio > 50.0) { System.out.println("You win!"); } System.out.println(); } }

Write a method called stripHtmlTags that accepts a Scanner representing an input file containing an HTML web page as its parameter, then reads that file and prints the file's text with all HTML tags removed. A tag is any text between the characters < and > . For example, consider the following text: <html> <head> <title>My web page</title> </head> <body> <p>There are many pictures of my cat here, as well as my <b>very cool</b> blog page, which contains <font color="red">awesome stuff about my trip to Vegas.</p> Here's my cat now:<img src="cat.jpg"> </body> </html> If the file contained these lines, your program should output the following text: My web page There are many pictures of my cat here, as well as my very cool blog page, which contains awesome stuff about my trip to Vegas. Here's my cat now: You may assume that the file is a well-formed HTML document and that there are no < or > characters inside tags.

public void stripHtmlTags(Scanner input) { while(input.hasNextLine()){ String line=input.nextLine(); while(line.contains("<")||line.contains(">")){ int index1= line.indexOf("<"); int index2=line.indexOf(">"); if(index1==0){ line=line.substring(index2+1); }else{ line=line.substring(0,index1)+line.substring(index2+1); } } System.out.println(line); } }

Write a method named countCoins that accepts as its parameter a Scanner for an input file whose data represents a person's money grouped into stacks of coins. Your method should add up the cash values of all the coins and print the total money at the end. The input consists of a series of pairs of tokens, where each pair begins with an integer and is followed by the type of coin, which will be either "pennies" (1 cent each), "nickels" (5 cents each), "dimes" (10 cents each), or "quarters" (25 cents each), case-insensitively. A given coin might appear more than once on the same line. For example, if the input file contains the following text: 3 pennies 2 quarters 1 pennies 3 nickels 4 dimes 3 pennies are worth 3 cents, and 2 quarters are worth 50 cents, and 1 penny is worth 1 cent, and 3 nickels are worth 15 cents, and 4 dimes are worth 40 cents. The total of these is 1 dollar and 9 cents, therefore your method would produce the following output if passed this input data. Notice that the method should show exactly two digits after the decimal point, so it says 09 for 9 cents: Total money: $1.09 Here is a second example. Suppose the input file contains the following text. Notice the capitalization and spacing: 12 QUARTERS 1 Pennies 33 PeNnIeS 10 niCKELs Then your method would produce the following output: Total money: $3.84 You may assume that the file contains at least 1 pair of tokens. You may also assume that the input is valid; that the input has an even number of tokens, that every other token is an integer, and that the others are valid coin types.

public void countCoins(Scanner in) { int sum = 0; int n = 0; String unit=""; while(in.hasNext()) { if (in.hasNextInt()) { n = in.nextInt(); } else { unit = in.next(); unit = unit.toLowerCase(); if (unit.equals("pennies")) { sum += n; } else if (unit.equals("nickels")) { sum += n * 5; } else if (unit.equals("dimes")) { sum += n * 10; } else if (unit.equals("quarters")){ sum += n * 25; } else { } } } System.out.printf("Total money: $%.2f", 0.01 * sum); }

Write a method named evenNumbers that accepts a Scanner as a parameter reading input from a file containing a series of integers, and report various statistics about the integers. You may assume that there is at least one integer in the file. Report the total number of numbers, the sum of the numbers, the count of even numbers and the percent of even numbers. For example, if a Scannerinput on file numbers.txt contains the following text: 5 7 2 8 9 10 12 98 7 14 20 22 then the call evenNumbers(input); should produce the following output: 12 numbers, sum = 214 8 evens (66.67%)

public void evenNumbers(Scanner input) { int n = 0; int sum = 0; int ne = 0; int num; while (input.hasNextInt()) { num = input.nextInt(); n++; sum += num; if (num % 2 == 0) { ne++; } } System.out.println(n + " numbers, sum = " + sum); System.out.printf("%d evens (%.2f%%)", ne, 100.0*ne/n); }

Write a method named flipLines that accepts as its parameter a Scanner for an input file and that writes to the console the same file's contents with successive pairs of lines reversed in order. For example, if the input file contains the following text: Twas brillig and the slithy toves did gyre and gimble in the wabe. All mimsey were the borogroves, and the mome raths outgrabe. "Beware the Jabberwock, my son, the jaws that bite, the claws that catch, Beware the JubJub bird and shun the frumious bandersnatch." The program should print the first pair of lines in reverse order, then the second pair in reverse order, then the third pair in reverse order, and so on. Therefore your method should produce the following output to the console: did gyre and gimble in the wabe. Twas brillig and the slithy toves and the mome raths outgrabe. All mimsey were the borogroves, "Beware the Jabberwock, my son, Beware the JubJub bird and shun the jaws that bite, the claws that catch, the frumious bandersnatch." Notice that a line can be blank, as in the third pair. Also notice that an input file can have an odd number of lines, as in the one above, in which case the last line is printed in its original position. You may not make any assumptions about how many lines are in the Scanner.

public void flipLines(Scanner in) { String line1, line2; while (in.hasNextLine()) { line1 = in.nextLine(); if (in.hasNextLine()) { line2 = in.nextLine(); System.out.println(line2); } System.out.println(line1); } }

Write a method leetSpeak that accepts two parameters: a Scanner representing an input file, and a PrintStream representing an output file. Your method should convert the input file's text to "leet speak" (aka 1337 speak), an internet dialect where various letters are replaced by other letters/numbers. Output the leet version of the text to the given output file. Preserve the original line breaks from the input. Also wrap each word of input in parentheses. Perform the following replacements: Original character 'Leet' character o 0 l (lowercase L) 1 e 3 a 4 t 7 s (at the end of a word only) Z For example, if the input file lincoln.txt contains the following text: four score and seven years ago our fathers brought forth on this continent a new nation And your method is called in the following way: Scanner input = new Scanner(new File("lincoln.txt")); PrintStream output = new PrintStream(new File("leet.txt")); leetSpeak(input, output); Then after the call, the output file leet.txt should contain the following text: (f0ur) (sc0r3) (4nd) (s3v3n) (y34rZ) (4g0) (0ur) (f47h3rZ) (br0ugh7) (f0r7h) (0n) (7hiZ) (c0n7in3n7) (4) (n3w) (n47i0n) You may assume that each token from the input file is separated by exactly one space. Hint: You may want to use the String object's replace method, which is used as follows: String str = "mississippi"; str = str.replace("s", "*"); // str = "mi**i**ippi"

public void leetSpeak(Scanner input, PrintStream output) { while(input.hasNextLine()) { Scanner line = new Scanner(input.nextLine()); while (line.hasNext()) { String word = line.next(); word = word.replace("o", "0"); word = word.replace("l", "1"); word = word.replace("e", "3"); word = word.replace("a", "4"); word = word.replace("t", "7"); int n = word.length(); if (word.charAt(n-1) == 's') { word = word.substring(0, n-1) + "Z"; } word = "(" + word + ")"; output.print(word + " "); } output.println(); } }

Write a method named printBox that accepts two parameters: a Scanner representing an input file, and an integer representing the length of the longest line of input in that file. Your method should print the contents of the file to the console, but print them inside a box figure. For example, if the file example.txt contains the following input data: This is some text here. Then the following would be the output of your method, when passed a Scanner on that file and the integer 12 as parameters: +--------------+ | This is some | | text here. | +--------------+

public void printBox(Scanner in, int n) { String h = "+-"; for (int i=0; i<n; i++) { h += "-"; } h += "-+"; System.out.println(h); String line; while(in.hasNextLine()){ line = in.nextLine(); System.out.print("| " + line); for (int i=0; i < (n-line.length()); i++) { System.out.print(" "); } System.out.println(" |"); } System.out.println(h); }

The following input file contains 17 total tokens that could be read by a Scanner. What are they? Hello there,how are you? I am "very well", thank you. 12 34 5.67 (8 + 9) "10" token 1-17 # of tokens read as an int, real number or string

token #1 Hello token #2 there,how token #3 are token #4 you? token #5 I token #6 am token #7 "very token #8 well", token #9 thank token #10 you. token #11 12 token #12 34 token #13 5.67 token #14 (8 token #15 + token #16 9) token #17 "10" # of tokens that can be read as an integer 2 # of tokens that can be read as a real number 3 # of tokens that can be read as a string 17


Kaugnay na mga set ng pag-aaral

CMS 2 Assignment 6: Attracting and Retaining Talent

View Set

Chapter 12: The Postpartum Woman

View Set

Sheerpath Quiz 7 Parenteral and Syringe

View Set

NUR 3010 - Week 8 Content (Hypertension)

View Set