ITERATION QUIZ QUESTIONS WITH 100%
CORRECT ANSWERS!!
QUESTION 1:
Write a method that loops until the user inputs the correct secret password or
until the user fails to enter the correct password 10 times. The secret password
the program should look for is the String "secret"
Assume that a Scanner object called input has been correctly initialized.
ANSWER: C
public void secretPassword()
{
int count = 0;
while(true)
{
if(count == 10)
{
System.out.println("You are locked out!");
return;
}
String readLine = input.nextLine();
if(readLine.equals("secret"))
{
System.out.println("Welcome!");
return;
}
count++;
}
}
QUESTION 2:
What would the method call myMethod("Karel The Dog", 'e') output?
public int myMethod(String x, char y)
{
int z = 1;
for(int i = 0; i < x.length(); i++)
{
if(x.charAt(i) == y)
{
z++;
}
}
, return z;
}
ANSWER: C
3
QUESTION 3:
What kind of error would the method call myMethod("Frog") cause?
public void myMethod(String x)
{
for(int i = 0; i <= x.length(); i++)
{
System.out.println(x.substring(i, i+1));
}
}
ANSWER: B
Runtime Error: String index out of range
QUESTION 4:
What will the call to the method funWithNumbers(314159) print to the screen?
public void funWithNumbers(double myDouble)
{
int myInt = (int) myDouble;
String myString = "";
while(myInt != 0)
{
myString = myInt % 10 + myString;
myInt /= 10;
}
System.out.println(myString);
}
ANSWER: A
314159
QUESTION 5:
What does the call to the method someMethod(3,1) output?
public int someMethod(int x, int y)
{
int sum = 0;
while (x < 10)
{
sum += x % y;
x++;
y++;
}
return sum;
}