java - Code skips if statement even though parameters are correct -
this code supposed take input customer in format "$(amount of money)". if statement check first character in string payment equals '$' doesn't set off if statement it keeps reading invalid payment.
double money = 0; string payment = input.next(); string $ = "$"; string test = payment.substring(0); if (test.equals($)) { system.out.println("you entered " + payment); payment = payment.substring(1, payment.length() - 1); money = double.parsedouble(payment); if ( money < sum ) { system.out.println("not enough money. system terminating."); system.exit(0); } system.out.println(payment); } else { system.out.println("invalid coin or note. try again."); payment = input.next(); }
payment.substring(0)
returns entire string, want compare "$"
payment.substring(0,1)
, or compare payment.charat(0)
'$'
.
so either :
string test = payment.substring(0,1); if (test.equals($)) {
or
if (payment.charat(0) == '$') {
will work.
another option is:
if (payment.startswith ($)) {
Comments
Post a Comment