Chapter+3+String+Compare
Comparing Strings and Generating Random Numbers
Chapter Overview
Chapter 3 focuses on comparing strings and generating random numbers in programming.
User Input and Conditional Statements
Age Input Example
Code Example:
Scanner in = new Scanner(System.in);
System.out.print("enter your age: ");
int age = in.nextInt();
in.nextLine();
if(age == 16)
System.out.println("your first year eligible to drive");
else
System.out.println("not your first year of eligibility");Name Input Example
Code Example:
Scanner in = new Scanner(System.in);
System.out.print("enter your name: ");
String name = in.nextLine();
if(name == "Mr. Ellis") {
System.out.print("you are the teacher");
} else {
System.out.print("you are a student");
}String Comparison
Comparing Strings
Strings should not be compared using
==, as it checks for reference equality.Use the
.equals()method to compare string values:
String name = "Mr. Ellis";
if(name.equals("Mr. Ellis"))
System.out.print("this works");Case Sensitivity
String comparison using
.equals()is case-sensitive:
String str = "Mr. Ellis";
if (str.equals("Mr. Ellis")) // prints "yes"
if (str.equals("mr. ellis")) // does not print "yes"Correct String Comparison
Always use
.equals()for string comparisons:
Scanner in = new Scanner(System.in);
String name = in.nextLine();
if(name.equals("Mr. Ellis")) {
System.out.print("you are the teacher");
} else {
System.out.print("you are a student");
}Ignoring Case in Comparisons
To ignore case, use
.toLowerCase()or.toUpperCase():
String str = "Mr. Ellis";
if (str.toLowerCase().equals("mr. ellis"))
System.out.print("yes"); // prints "yes"Generating Random Numbers
Random Class Overview
Import statement must be included:
import java.util.Random;Create an instance of the
Randomclass to generate random numbers:
Random rand = new Random();Use the
nextInt(max)method to generate a random number from 0 to max (exclusive):
int myRand = rand.nextInt(10); // random number from 0-10Random Number Example
Code Example:
Random myRand = new Random();
int randNum = myRand.nextInt(10);
System.out.print("random number: " + randNum);
if(randNum == 1)
System.out.print("you’re number one!");