SJSU/Udacity CS046

Problem Set 5

  1. Loops
  2. Looping a String
  3. Product 1 to n
  4. Count Non-Vowels
  5. Do
  6. Average
  7. Blocks in a Loop
  8. Variable Blocks in a Loop
  9. Coin Toss
  10. Sum of Odd Digits
  11. Random Word Permutations
  12. Get Substrings

Average

Look at this loop to find the first space in String str. What is the value of ch and position at the end of the loop?

String str ="Udacity";
boolean found = false;
String ch = "?";
int position = 0;
while (!found && position < str.length())
{
   ch = str.substring(position, position + 1);
   if (ch.equals(" "))
   {
      found = true;
   }
   else
   {
      position++;
   }
}
"y" 7

Look at this loop to find the first space in String str. What is the value of ch and position at the end of the loop?

String str ="";
boolean found = false;
String ch = "?";
int position = 0;
while (!found && position < str.length())
{
   ch = str.substring(position, position + 1);
   if (ch.equals(" "))
   {
      found = true;
   }
   else
   {
      position++;
   }
}
"?" 0

We are processing a series of words input by the user. We want to terminate the loop if there are adjacent duplicates. For eample, this sequence of words will terminate after the the second word cat: The pretty little cat cat is named Eliza. Complete the code below to acconmplish this. Do not use break or continue

      Scanner in = new Scanner (System.in);

      boolean duplicate  = false;
      String input = "";
      while (!duplicate && in.hasNext())
      {
         String previous = input;
         input = in.next();
         if (input.equals(previous))
         {
             //...your code here
         }
         else
         {
             //do some processing
         }
      }
duplicate = true;

What do the following nested loops display?

for (int i = 0; i < 3; i++)
{
   for (int j = 0; j < 4; j++)
   {
      System.out.print(i + j);
   }
   System.out.print(" ");
}
0123 1234 2345

Complete the code fragment to generate a random integer x between 0 and 10 including 0, excluding 10. (<= 0 x < 10)

Random generator = new Random();
int x = ________________ ;
generator.next(10)

Complete the code fragment below to generate a random integer x between 1 and 10 (inclusive) (<= 1 x <= 10)

Random generator = new Random();
int x = ________________ ;
generator.next(10) + 1

Complete the code random double between 0 and 100

Random generator = new Random();
double d = ________________ ;
generator.nextDouble() * 100

Problem on this page?

Your name:

Your email address:

Problem description:

To protect against spam robots, please answer this simple math problem:
× =