Fence Post & While Loop starters

posted by: Mr. Bergquist 24 November 2013 No Comment

Taken directly from Practice It!:  (click the problem name link or try the problem directly)

Fence Post:

BJP3 Self-Check 5.12: printLetters 

Consider the flawed method printLetters that follows, which accepts a string as its parameter and attempts to print the letters of the string, separated by dashes. For example, the call of printLetters("Rabbit") should print R-a-b-b-i-t. The initial code shown is incorrect. Correct it to produce the desired behavior. (Your method should print nothing if the empty string ("") is passed.)

public static void printLetters(String text) {
    for (int i = 0; i < text.length(); i++) {
        System.out.print(text.charAt(i) + "-");
    }
    System.out.println();   // to end the line of output
}
.

While Loops:

BJP3 Exercise 5.12: printAverage

Write a method named printAverage that accepts a Scanner for the console as a parameter and repeatedly prompts the user for numbers. Once any number less than zero is typed, the average of all non-negative numbers typed is displayed. Display the average as a double, and do not round it. For example, a call to your method might look like this:

Scanner console = new Scanner(System.in);
printAverage(console);

The following is one example log of execution for your method:

Type a number: 7
Type a number: 4
Type a number: 16
Type a number: -4
Average was 9.0

If the first number typed is negative, do not print an average. For example:

Type a number: -2
.

OPTIONAL, but a good Self-Check problem to Warm Up for Project 5: Guessing Game.

BJP3 Exercise 5.6: makeGuesses Write a method named makeGuesses that will guess numbers between 1 and 50 inclusive until it makes a guess of at least 48. It should report each guess and at the end should report the total number of guesses made. Below is a sample execution:

guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5
.
About: Practice-It! web application and problems are copyright © Marty Stepp unless otherwise specified. Some problems are copyright © Pearson. This site is not directly affiliated or associated with Pearson or with any particular textbook or online resource. Any non-educational usage of the content on this site is expressly forbidden without written permission. All rights reserved.
1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.00 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>