Results 1 to 3 of 3

Thread: Case question

  1. #1
    cupOJava is offline Member
    Join Date
    Nov 2012
    Posts
    5
    Rep Power
    0

    Default 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! ");
    }*/

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    757
    Rep Power
    7

    Default 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:

    Java Code:
    if (response.equals("Y")) {
        // do something.
    }

  3. #3
    cupOJava is offline Member
    Join Date
    Nov 2012
    Posts
    5
    Rep Power
    0

Similar Threads

  1. How to use Contains - without case sensitivity?
    By Russell411 in forum New To Java
    Replies: 12
    Last Post: 11-07-2012, 02:53 PM
  2. Case statements in JPA
    By KavithaShivaram in forum JPA
    Replies: 0
    Last Post: 04-27-2012, 02:20 PM
  3. Case help!!!
    By cloverrea in forum New To Java
    Replies: 1
    Last Post: 10-13-2011, 12:00 AM
  4. Question about Line object w/ switch case
    By kraigballa in forum New To Java
    Replies: 8
    Last Post: 10-11-2011, 08:00 PM
  5. case statement
    By skiing in forum New To Java
    Replies: 5
    Last Post: 05-07-2009, 12:13 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •