Java Reference
In-Depth Information
5.27
After the break statement in (a) is executed in the following loop, which statement
is executed? Show the output. After the continue statement in (b) is executed in the
following loop, which statement is executed? Show the output.
for ( int i = 1 ; i < 4 ; i++) {
for ( int j = 1 ; j < 4 ; j++) {
if (i * j > 2 )
break ;
for ( int i = 1 ; i < 4 ; i++) {
for ( int j = 1 ; j < 4 ; j++) {
if (i * j > 2 )
continue ;
System.out.println(i * j);
}
System.out.println(i * j);
}
System.out.println(i);
}
System.out.println(i);
}
(a)
(b)
5.10 Case Study: Checking Palindromes
This section presents a program that checks whether a string is a palindrome.
Key
Point
A string is a palindrome if it reads the same forward and backward . The words “mom,” “dad,”
and “noon,” for instance, are all palindromes.
The problem is to write a program that prompts the user to enter a string and reports
whether the string is a palindrome. One solution is to check whether the first character in the
string is the same as the last character. If so, check whether the second character is the same
as the second-to-last character. This process continues until a mismatch is found or all the
characters in the string are checked, except for the middle character if the string has an odd
number of characters.
Listing 5.14 gives the program.
think before you code
L ISTING 5.14
Palindrome.java
1 import java.util.Scanner;
2
3 public class Palindrome {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Prompt the user to enter a string
10 System.out.print( "Enter a string: " );
11 String s = input.nextLine();
12
13
input string
// The index of the first character in the string
14
int low = 0 ;
low index
15
16
// The index of the last character in the string
17
int high = s.length() - 1 ;
high index
18
19 boolean isPalindrome = true ;
20 while (low < high) {
21 if (s.charAt(low) != s.charAt(high)) {
22 isPalindrome = false ;
23
break ;
24 }
25
 
 
 
Search WWH ::




Custom Search