Question:

Can you help me with java?

by  |  earlier

0 LIKES UnLike

I'm trying to do an if-then-else statement that does something according to whether a y or n was inputted. What am I doing wrong?

if(keyboard.nextChar()='y' || keyboard.nextChar()='Y' )

{

System.out.println("What is the amount charged? ");

amountCharged = keyboard.nextFloat();

}

 Tags:

   Report

2 ANSWERS


  1. You are comparing a string ('y' and 'Y') using the equals ('=') operator. In Java this is fine for numbers, but in the case of strings, use the ".equals" method.

    if(keyboard.nextChar().equals('y') || keyboard.equals('Y' ))

    {

    System.out.println("What is the amount charged? ");

    amountCharged = keyboard.nextFloat();

    }

    and also when comparing, the correct operator is ('==') and not

    ('=') which is used for assigning values.


  2. try this:

    if( keyboard.nextChar() == 'y' || keyboard.nextChar() == 'Y'){

         //do something here

    }

    else if( keyboard.nextChar() == 'n' || keyboard.nextChar() == 'N'){

       //do something else here...

    }

    else{

       //neither y or n was pressed, handle that here...

    The problem is the equal sign in your statement...

    the sign = is an assignment statement like x = 5;

    the sign == is used to compare like if (x == 5);

    Good?

    }

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.