java - Converting String to Char with If/Else Statement -


this question has answer here:

i'm new programming , i've been searching days solution lab i'm working on. lab pretty simple , believe have logic down, when executing code, i'm not getting desired results. program asks input of 3 integers , 1 character. if character 's' program print sum of first 3 integers, if character 'p,' product, 'a,' average, , other character prints error.

below code. asks 3 integers , character result error, if type in 's,' 'p,' or 'a.'

any appreciated.

thanks, joe

    int n1, n2, n3;     string numberfromkb;     string charfromkb;     scanner keyboard = new scanner (system.in);      numberfromkb = joptionpane.showinputdialog("enter first number.");     n1 = integer.parseint(numberfromkb);      numberfromkb = joptionpane.showinputdialog("enter second number.");     n2 = integer.parseint(numberfromkb);      numberfromkb = joptionpane.showinputdialog("enter 3rd number.");     n3 = integer.parseint(numberfromkb);      charfromkb = joptionpane.showinputdialog(null, "enter character:");     if (charfromkb = "s")     {         system.out.println("sum of integers is: " + n1 + n2 + n3);     }     else if (charfromkb = "p")     {         system.out.println("product of integers is: " + n1 * n2 * n3);     }     else if (charfromkb = "a")     {         system.out.println("average of integers is: " + ((n1 + n2 + n3)/3f));     }     else      {         system.out.println("error!");     }  } 

}

you're using equal operator , assigning charfromkb equal "s"

instead should use string equals method, switch this:

if (charfromkb = "s") {         system.out.println("sum of integers is: " + n1 + n2 + n3); } 

with this:

if (charfromkb.equals("s")) {        system.out.println("sum of integers is: " + n1 + n2 + n3); { 

the equals operator "==" doesn't work strings. more on in link.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -