|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
What's wrong with the following code?
class EBayExpert { double FVFee( double salesPrice ) { double fee; if (salesPrice > 25.00) { fee = … } else if (salesPrice > 1000.00) { fee = … } else { // Less than 25: fee = … } return fee; } |
To compare two strings, do not use == — instead, use equals. That is,
String s1 = "hello"; s1.equals("hello") s1.equals("aloha") String s2 = s1.substring(3,5); String s3 = "aloha".substring(1,3); s2.equals(s3) |
While we're on the topic of comparing Strings, here are a few more useful methods:
equalsIgnoreCase compareTo |
import java.util.Scanner; class BankAccountTester2 { public static void main( String[] args ) { BankAccount b1 = new BankAccount(5000); // We're rich! String command; java.util.Scanner s = new java.util.Scanner( System.in ); // Prepare to read from the keyboard. System.out.println( "Do you want to add, remove, or query? " ); command = s.next(); // Reads the next word typed at the keyboard. // TO DO: check if command is "query", "add", or "remove", // and then call the appropriate method. System.out.println( "The balance is now " + b1.getBalance() ); } } |
1 The book mentions what's going on: ==, given two object-references (arrows), just reports whether the two arrows point to the same object. So: even if two different String objects have the same letters [see book for a memory-diagram], == will report them as different. On the other hand, this is the correct behavior for, say, BankAccounts: even if two different BankAccounts have the same balance, == still reports them as different. ↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Mar.16 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |