Java Reference
In-Depth Information
4
public
void
Test(String s) {
5 text = s;
6 }
7
8 public static void main(String[] args) {
9 Test test = new Test( "ABC" );
10 System.out.println(test);
11 }
12 }
9.11
Show the output of the following code.
public class Test {
public static void main(String[] args) {
System.out.println( "Hi, ABC, good" .matches( "ABC " ));
System.out.println( "Hi, ABC, good" .matches( ".*ABC.*" ));
System.out.println( "A,B;C" .replaceAll( ",;" , "#" ));
System.out.println( "A,B;C" .replaceAll( "[,;]" , "#" ));
String[] tokens = "A,B;C" .split( "[,;]" );
for ( int i = 0 ; i < tokens.length; i++)
System.out.print(tokens[i] +
" " );
}
}
9.3 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.
To implement this idea, use two variables, say low and high , to denote the position of the
two characters at the beginning and the end in a string s , as shown in Listing 9.1 (lines 22,
25). Initially, low is 0 and high is s.length() - 1 . If the two characters at these positions
match, increment low by 1 and decrement high by 1 (lines 31-32). This process continues
until ( low >= high ) or a mismatch is found.
VideoNote
Check palindrome
L ISTING 9.1 CheckPalindrome.java
1
import java.util.Scanner;
2
3 public class CheckPalindrome {
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
12
13
String s = input.nextLine();
input string
if (
isPalindrome(s)
)
 
 
Search WWH ::




Custom Search