RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lect07b
comparisons; functions returning booleans

A Question

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;
    }

comparing Strings

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)
You can try evaluating each of these in codepad, along with something that gives a wrong1 answer: s2 == s3.

While we're on the topic of comparing Strings, here are a few more useful methods:

equalsIgnoreCase
compareTo
(Let's look at the documentation, and make a couple of of calls to these methods.)

Task: A program comparing strings

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() );
    }
  }
(Here is our code for BankAcccount.java.)


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.      

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Mar.16 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme