In: Computer Science
What (if anything) is wrong with the following code:
int redCount = 0, blueCount = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please make a selection: ");
String option = scan.next();
while(!option.startsWith("q") || !option.startsWith("Q"))
{
if(option.equals("red"))
{
redCount++;
}
else
{
blueCount++;
}
System.out.println("Please enter another value: ");
option = scan.next();
}
System.out.println("Red: " + redCount + ", Blue: " + blueCount);
|
The condition is not a boolean expression. |
||
|
A variable is out of scope. |
||
|
There is nothing wrong with this code. |
||
|
It will result in an infinte loop. |
||
|
It contains a logic error that will cause it to function incorrectly. |
What (if anything) is wrong with the following code:
int redCount = 0, int blueCount = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please make a selection: ");
String option = scan.next();
while(!option.toLowerCase().startsWith("q"))
{
if(option.equals("red"))
{
redCount += 1;
}
else
{
blueCount += 1;
}
System.out.println("Please enter another value: ");
option = scan.next();
}
System.out.println("Red: " + redCount + ", Blue: " + blueCount);
|
A variable is out of scope. |
||
|
The condition is not a boolean expression. |
||
|
It will result in an infinte loop. |
||
|
There is nothing wrong with this code. |
||
|
It contains a logic error that will cause it to function incorrectly. |
QUESTION (1):-
OPTION (D) It will result in an infinte loop.
correct code given below
int redCount = 0, blueCount = 0;
Scanner scan = new
Scanner(System.in);
System.out.println("Please make a
selection: ");
String option = scan.next();
while(!(option.startsWith("q") ||
option.startsWith("Q")))
{
if(option.equals("red"))
{
redCount++;
}
else
{
blueCount++;
}
System.out.println("Please enter
another value: ");
option = scan.next();
}
System.out.println("Red: " +
redCount + ", Blue: " + blueCount);
QUESTION (2):-
OPTION (D) There is nothing wrong with this code.
correct code given below
int redCount = 0,blueCount = 0;
Scanner scan = new
Scanner(System.in);
System.out.println("Please make a
selection: ");
String option = scan.next();
while(!option.toLowerCase().startsWith("q"))
{
if(option.equals("red"))
{
redCount += 1;
}
else
{
blueCount += 1;
}
System.out.println("Please enter
another value: ");
option = scan.next();
}
System.out.println("Red: " +
redCount + ", Blue: " + blueCount);
NOTE: second code have invalid syntax in line number 1
int redCount = 0, int blueCount = 0;
int declare two times , so option not available in list , i remove one int then program working fine.
// If any doubt please comment