Page 146 - Introduction to Programming with Java: A Problem Solving Approach
P. 146
112 Chapter 4 Control Statements
/******************************************************************
*
SentenceTester.java
Dean & Dean
This program checks for period at the end of line of input.
*******************************************************************/
*
*
*
import java.util.Scanner;
public class SentenceTester
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String sentence;
int lastCharPosition;
System.out.println("Enter a sentence:");
sentence = stdIn.nextLine();
}
lastCharPosition = sentence.length() - 1;
if (sentence.charAt(lastCharPosition) != '.')
{
System.out.println(
entAryp-aygouor sePntDeFnce Enenedhs a npecrieodr!"); // end class SentenceTester
}
// end main
}
"Invalid
This condition checks for proper termination.
Figure 4.4 SentenceTester program
you have a compound condition, each part of the compound condition evaluates to either true or false, and then the parts combine to produce a composite true or false for the whole compound condition. The combining rules are what you might expect: When you “and” two conditions together, the combination is true only if the first condition is true and the second condition is true. When you “or” two conditions together, the combination is true if the first condition is true or the second condition is true. You’ll see plenty of examples as the chapter progresses.
&& Operator Example
Let’s begin our discussion of logical operators with an example that uses the && operator. (Note: && is pro- nounced “and”). Suppose you want to print “OK” if the temperature is between 50 and 90 degrees and print “not OK” otherwise:
not OK
50°
OK
90°
not OK