-
Case question
Could someone look at my code and tell me why is that when the user enters the appropriate letter (example: user selects N) the console is not printing out the system.out.println statement?
Thanks in advance.
/*String operationType = input.nextLine();
int num =0;
if (operationType == "N")
{
num = 1;
}
else if (operationType == "D")
{
num = 2;
}
else if (operationType == "M")
{
num = 3;
}
else if (operationType == "Q")
{
num = 4;
}
switch(num)
{
case 1: //N
System.out.println("Please enter the product name: ");
String productName1 = input.nextLine();
productArray[Inventory.getNumOfObjects()] = new Inventory(productName1);
Inventory.setProductName(productName1);
System.out.println("Any units in stock or unit price to declare? (Y or N): ");
String response = input.nextLine();
if(response == "Y")
{
System.out.println("Enter the number of units in stock: ");
unitsInStock = input.nextInt();
System.out.println("Now enter the price of each unit: $ ");
unitPrice = input.nextDouble();
System.out.println("New Inventory Succesfull! ");
}
else if(response == "N")
{
System.out.println("New Inventory Successfull! ");
}*/
-
Re: Case question
When you comparing the value of two strings you must use the equals() or equalsIgnoreCase() methods. You can't use the == operator, because this operator will compare whether these two strings object refer to the same object in memory.
So your code should be written like:
Code:
if (response.equals("Y")) {
// do something.
}
-
Re: Case question
That was it. Thank you so much!