You are on page 1of 32

Java: Selection & String

The Institute of Finance Management


Faculty of Computing, Information Systems and
Mathematics
Computer Science Department
Selection
• The program can decide which statements to execute based on a
condition.
• Like all high-level programming languages, Java provides selection
statements: statements that let you choose actions with alternative
courses.
• E.g if you enter a negative value for radius, the program should be
able to respond according

if (radius < 0) {
System.out.println("Incorrect input");
}
else {
area = radius * radius * 3.14159;
System.out.println("Area is " + area);
}
Selection
• Selection statements use conditions that are
Boolean expressions.
• A Boolean expression is an expression that
evaluates to a Boolean value: true or false.
• The boolean data type declares a variable with
the value either true or false.
• Selection statements includes:
– If statement
– Two-Way if-else Statements
– Switch Statement
If statement
import java.util.Scanner;
public class SimpleIfDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0)
System.out.println("HiFive");

if (number % 2 == 0)
System.out.println("HiEven");
}
}
If statement
• A one-way if statement performs an action if
the specified condition is true.
• If the condition is false, nothing is done.
• But what if you want to take alternative
actions when the condition is false?
Two-Way if-else Statements
• An if-else statement decides the execution
path based on whether the condition is true
or false

if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Two-Way if-else Statements
• If the boolean-expression evaluates to true, the statement(s)
for the true case are executed; otherwise, the statement(s)
for the false case are executed. For example, consider the
following code:

if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of
radius " + radius + " is " + area);
}
else{
System.out.println("Negative input");
}
Nested if and Multi-Way if-else
Statements
• An if statement can be inside another if statement to
form a nested if statement

if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
Nested if and Multi-Way if-else
Statements
switch Statements
• A switch statement executes statements
based on the value of a variable or an
expression.
• Overuse of nested if statements makes a
program difficult to read. Java provides a
switch statement to simplify coding for
multiple conditions.
switch Statements
switch (status) {
case 0: compute tax for single filers;
break;
case 1: compute tax for married jointly or qualifying widow(er);
break;
case 2: compute tax for married filing separately;
break;
case 3: compute tax for head of household;
break;
default: System.out.println("Error: invalid
status");
System.exit(1);
}
switch Statements
• Let us write a program to find out the Chinese
Zodiac sign for a given year.
• The Chinese Zodiac is based on a twelve-year
cycle, with each year represented by an
animal— monkey, rooster, dog, pig, rat, ox,
tiger, rabbit, dragon, snake, horse, or sheep—
in this cycle
The Chinese Zodiac
import java.util.Scanner;
public class ChineseZodiac {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
switch (year % 12) {
case 0: System.out.println("monkey"); break;
case 1: System.out.println("rooster"); break;
case 2: System.out.println("dog"); break;
case 3: System.out.println("pig"); break;
case 4: System.out.println("rat"); break;
case 5: System.out.println("ox"); break;
case 6: System.out.println("tiger"); break;
case 7: System.out.println("rabbit"); break;
case 8: System.out.println("dragon"); break;
case 9: System.out.println("snake"); break;
case 10: System.out.println("horse"); break;
case 11: System.out.println("sheep");
}
}
}
Class Exercise
• Write a switch statement that displays Sunday,
Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6,
accordingly.
Common Errors and Pitfalls
• Forgetting necessary braces
• Ending an if statement in the wrong place,
• Mistaking == for =
• Dangling else clauses are common errors in
selection statements.
• Duplicated statements in if-else statements
and testing equality of double values are
common pitfalls.
Logical Operators
• The logical operators !, &&, ||, and ^ can be used to
create a compound Boolean expression.
Debugging
• Debugging is the process of finding and fixing
errors in a program.
– Syntax errors are easy to find and easy to correct
because the compiler gives indications as to where
the errors came from and why they are there.
– Runtime errors are not difficult to find either, because
the Java interpreter displays them on the console
when the program aborts.
– Finding logic errors, on the other hand, can be very
challenging to find
Debugging
• Logic errors are called bugs. The process of
finding and correcting errors is called debugging.
• A common approach to debugging is to use a
combination of methods to help pinpoint the part
of the program where the bug is located.
• For short and Simple program the two method
may be used for debugging
– Hand-trace the program (i.e., catch errors by reading
the program)
– Insert print statements in order to show the values of
the variables or the execution flow of the program
Debugging
• For Large and Complex program, the most
effective approach is to use a debugger utility
• JDK includes a command-line debugger
• The debugger utilities let you follow the
execution of a program and support most of the
following helpful features.
1. Executing a single statement at a time
2. Tracing into or stepping over a method
3. Setting breakpoints
4. Displaying variables
5. Displaying call stacks
6. Modifying variables
Unicode and ASCII code
• Computers use binary numbers internally.
• A character is stored in a computer as a sequence
of 0s and 1s.
• Mapping a character to its binary representation
is called encoding
• Java supports Unicode, an encoding scheme
established by the Unicode Consortium to
support the interchange, processing, and display
of written texts in the world’s diverse languages
Unicode and ASCII code
• Most computers use ASCII (American Standard Code for
Information Interchange), an 8-bit encoding scheme for
representing all uppercase and lowercase letters, digits,
punctuation marks, and control characters.

• Thus, for example, the following statements are equivalent:


char letter = 'A';
char letter = '\u0041'; // Character A's Unicode is 0041
The String Type
• A string is a sequence of characters
• The char type represents only one character.
• To represent a string of characters, use the
data type called String.
• For example, the following code declares
message to be a string with the value
"Welcome to Java".
String message = "Welcome to Java";
The String Type
• String is a predefined class in the Java library,
just like the classes System and Scanner.
• Simple Methods for String Objects
String: Getting String Length
• You can use the length() method to return the
number of characters in a string.
• For example, the following code.

String message = "Welcome to Java";


System.out.println("The length of " +
message + " is " + message.length());
Concatenating Strings
• You can use the concat method to concatenate two
strings.
• The statement shown below, for example,
concatenates strings s1 and s2 into s3:
String s3 = s1.concat(s2);
• You can use the plus (+) operator to concatenate two
strings, so the previous statement is equivalent to:
String s3 = s1 + s2;
Converting Strings
• The toLowerCase() method returns a new string with all
lowercase letters.
• The toUpperCase() method returns a new string with all
uppercase letters.
• For example,
"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
Comparing Strings
• The String class contains the methods as
shown in Table below
Comparing Strings
• How do you compare the contents of two strings?
• You might attempt to use the == operator, as follows:
if (string1 == string2)
System.out.println("string1 and string2 are the same object");
else
System.out.println("string1 and string2 are different objects");

• However, the == operator checks only whether string1


and string2 refer to the same object; it does not tell you
whether they have the same contents.
• Therefore, you cannot use the == operator to find out whether
two string variables have the same contents
• Instead, you should use the equals method.
Comparing Strings
if (string1.equals(string2))
System.out.println("string1 and string2 have the same
contents");
else System.out.println("string1 and string2 are not
equal");

• The compareTo method can also be used to compare two


strings. For example, consider the following code:
s1.compareTo(s2)

• The actual value returned from the compareTo method


depends on the offset of the first two distinct characters in s1
and s2 from left to right.
• The method returns the value 0 if s1 is equal to s2, a
value less than 0 if s1 is lexicographically (i.e., in terms of
Unicode ordering) less than s2, and a value greater than
0 if s1 is lexicographically greater than s2
Comparing Strings
import java.util.Scanner;
public class OrderTwoCities {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two cities
System.out.print("Enter the first city: ");
String city1 = input.nextLine();
System.out.print("Enter the second city: ");
String city2 = input.nextLine();
if (city1.compareTo(city2) < 0)
System.out.println("The cities in alphabetical order are " +
city1 + " " + city2)
else
System.out.println("The cities in alphabetical order are " +
city2 + " " + city1);
}
}
END

You might also like