"Program execution skips the "if" statement"!
Hello Everyone,
I am trying to calculate and print the total cost of movie tickets by asking the user whether he wants to buy a ticket or not.
In the code I have an output statement which says to enter yes or no. My question tells me even if the user enter Yes in different ways such as Yes,YES,YeS and yEs,
below is my program which for now takes "Yes" as the user input and carries out the process.
Code :
/**
* Write a description of class Lab3P2 here.
* Ticket printing
* @author (Sai)
* @version (7May)
*/
import java.io.*;
import java.util.Scanner;
public class Lab3P3
{
public static void main(String[] args) throws IOException{
//String choice;
double a1,c1,sc,s;
double adult = 15.00;
double child = 11.00;
double Scitizen = 9.50;
double Student = 12.00;
System.out.println("Movie Tickets\n");
System.out.println("Adult $15.00\n Child $11.00");
System.out.flush();
Scanner input = new Scanner( System.in );
System.out.println("Do you wish you buy a ticket:(Yes/No)");
//choice = input.nextLine();
String choice = input.nextLine();
[COLOR="#FF0000"]if(choice == "Yes")[/COLOR]
{
System.out.println("How Many adult tickets would you wish to buy");
a1 = input.nextInt();
a1 = a1*adult;
System.out.println("How Many Child tickets would you wish to buy");
c1 = input.nextInt();
c1 = c1*child;
System.out.println("How Many SenoirCitizen tickets would you wish to buy");
sc = input.nextInt();
sc = sc*Scitizen;
System.out.println("How Many Student tickets would you wish to buy");
s = input.nextInt();
s = s*Student;
System.out.println("Total cost of Movie Tickets is: $" + (a1+c1+sc+s));
System.out.println("Thank you,Have a nice Day\n");
}
else
System.out.println("Thank you,Have a nice Day\n");
}
}
Does not execute this statement for some reason : if(choice == "Yes")
The program compiles with no syntax errors but the problem is it skips the highlighted part in the program and jumps to the else statement and prints out the thank you message.
Can anyone please help me out where I am doing a mistake!
regards
Antony
Re: "Program execution skips the "if" statement"!
Hello Antony!
You should use the String's equals() (or better in your case equalsIgnoreCase()) method instead of the == operator when comparing Strings.