Java Reference
In-Depth Information
Display 6.8 String Processing Method with a Variable Number of Parameters (part 1 of 2)
Both methods use the parameter sentence as a local variable. If this
puzzles you, review the material on parameters in Chapters 4 and 5,
particularly Display 4.5 in Chapter 4.
1 public class Utility2
2{
3
/**
4
Returns the first argument with all occurrences of other arguments deleted;
5
*/
6
public static String censor(String sentence, String... unwanted)
7
{
8
for ( int i = 0; i < unwanted.length; i++)
9
sentence = deleteOne(sentence, unwanted[i]);
10
return sentence;
If you have trouble following this string
processing, review the subsection
entitled “String Processing” in Chapter 1.
11
}
12
/**
13
Returns sentence with all occurrences of oneUnwanted removed.
14
*/
15
private static String deleteOne(String sentence, String oneUnwanted)
16
{
17
String ending;
18
int position = sentence.indexOf(oneUnwanted);
19
while (position >= 0) //While word was found in sentence
20
{
21
ending = sentence.substring(position + oneUnwanted.length());
22
sentence = sentence.substring(0, position) + ending;
23
position = sentence.indexOf(oneUnwanted);
24
}
This is the file Utility2.java .
25
return sentence;
26
}
27
}
1
import java.util.Scanner;
This is the file
StringProcessingDemo.java .
2 public class StringProcessingDemo
3{
4
public static void main(String[] args)
5
{
6
System.out.println("What did you eat for dinner?");
7
Scanner keyboard = new Scanner(System.in);
8
String sentence = keyboard.nextLine();
9
sentence = Utility2.censor(sentence,
10
"candy", "french fries", "salt", "beer");
11
sentence = Utility2.censor(sentence, " ,"); //Deletes extra commas
12
System.out.println("You would be healthier if you could answer:");
13
System.out.println(sentence);
14
}
15
}
(continued)
 
Search WWH ::




Custom Search