This question already has an answer here:
- How do I compare strings in Java? 23 answers
I have the following code and it all executes correctly [commented out first if-statement and ran remaining code] except the if statement about "Are you ready for a quiz? (Y/N) ". The default response is always given of "Please enter a valid response." I have tried Y and N as options with the same result. When I do a println the ready variable is taking the right input - its just not interpreting the input for the desired output.
Here is my code:
import java.util.Scanner;
public class LittleQuiz {
public static void main( String[] args ) {
Scanner keyboard = new Scanner( System.in );
String ready;
int answer_q1, answer_q2, answer_q3, total_right;
total_right = 0;
System.out.print( "Are you ready for a quiz? (Y/N) " );
ready = keyboard.nextLine();
if ( ready == "Y" ) {
System.out.println( "Okay, here it comes!\n" );
System.out.println( "Q1) What is the capital of Alaska?" );
System.out.println( " 1. Melbourne" );
System.out.println( " 2. Anchorage" );
System.out.println( " 3. Juneau\n" );
System.out.print( "Type Answer Choice > " );
answer_q1 = keyboard.nextInt();
if ( answer_q1 == 3) {
System.out.println( "\nThat's right.\n" );
total_right++;
}
else {
System.out.println( "\nThat's wrong, the correct answer is JUNEAU.\n" );
}
System.out.println( "Q2) Can you store the value \"cat\" in a variable of type int?" );
System.out.println( " 1. Yes" );
System.out.println( " 2. No\n" );
System.out.print( "Type Answer Choice > " );
answer_q2 = keyboard.nextInt();
if ( answer_q2 == 2) {
System.out.println( "\nThat's right.\n" );
total_right++;
}
else if ( answer_q2 == 1 ){
System.out.println( "\nSorry, \"cat\" is a string. int variables can only store numbers.\n" );
}
System.out.println( "Q3) What is the result of 9 + 6 / 3?" );
System.out.println( " 1. 5" );
System.out.println( " 2. 11" );
System.out.println( " 3. 15/3\n" );
System.out.print( "Type Answer Choice > " );
answer_q3 = keyboard.nextInt();
if ( answer_q3 == 2) {
System.out.println( "\nThat's correct.\n" );
total_right++;
}
else {
System.out.println( "\nThat's wrong, the correct answer is " + (9+6/3) + ".\n" );
}
System.out.println( "\nOverall, you got " + total_right + " out of 3 correct." );
System.out.println( "Thanks for playing!" );
}
else if ( ready == "N" ) {
System.out.print( "Bummer, come back when you are ready." );
}
else {
System.out.println( "Please enter a valid response." );
}
}
}
Aucun commentaire:
Enregistrer un commentaire