Docsity

Java Programming: Arithmetic Expressions, Strings, and Scanner Class - Prof. Zhongming Ma, Study notes of Computer Science

Partial preview of the text

Download Java Programming: Arithmetic Expressions, Strings, and Scanner Class - Prof. Zhongming Ma and more Study notes Computer Science in PDF only on Docsity!

CIS 304

Dr. Zhongming Ma

Java Review: Chapter 2

Introduction to

Java programming

The basic operators for arithmetic expressions

Operator Name Description

+ Addition Adds two operands.

  • Subtraction Subtracts the right operand from the left.

* Multiplication Multiplies the right and left operands.

/ Division Divides the right operand into the left. If both

are integers, the result is an integer.

How to code arithmetic expressions

 An arithmetic expression consists of one or more operands and

arithmetic operators.

 When an expression mixes int and double variables, Java

automatically casts the int types to double types. To keep the

decimal places, the variable that receives the result must be a

double.

The syntax for declaring and initializing a string variable

String variableName = value;

How to declare and initialize a string

String message1 = "Invalid data entry.";

String message2 = " ";

String message3 = "";

String message4 = null;

How to join strings

String firstName = "Bob"; // firstName is Bob

String lastName = "Smith"; // lastName is Smith

String name = firstName + " " + lastName; // Bob Smith

How to join a string and a number

double price = 14.95;

String priceString = "Price: $" + price; // Price: $14.

How to append one string to another with the + operator

firstName = "Bob"; // firstName is Bob lastName = "Smith"; // lastName is Smith name = firstName + " "; // name is Bob followed by a space name = name + lastName; // name is Bob Smith

How to append one string to another with the +=

operator

firstName = "Bob"; // firstName is Bob lastName = "Smith"; // lastName is Smith name = firstName + " "; // name is Bob followed by a space name += lastName; // name is Bob Smith

Example 1: New line String

System.out.println(“Code: JSPS\nPrice: $49.50");

Result

Code: JSPS

Price: $49.

Using API: do not reinvent wheels!

How to import Java classes

 The API for the J2SE provides a large library of classes that are

organized into packages.

 To use those classes, you need an import statement.

 To import one class from a package, specify the package name

followed by the class name. To import all classes in a package,

specify the package name followed by an asterisk (*). For

example, import java.util.*;

 All classes stored in the java.lang package are automatically

available to all Java programs. In other words, you don’t need to

write this import: import java.lang.*;

How to create an object from a class Syntax ClassName objectName = new ClassName(arguments); Examples

// creates a Scanner object named sc

Scanner sc = new Scanner(System.in);

How to call a method from an object Syntax objectName.methodName(arguments) Examples

double subtotal = sc.nextDouble();

// get a double entry from the console, such as the

command prompt.

// create a Scanner object Scanner sc = new Scanner(System.in); // read a string System.out.print("Enter product code: "); String productCode = sc.next(); // read a double value System.out.print("Enter price: "); double price = sc.nextDouble(); // read an int value System.out.print("Enter quantity: "); int quantity = sc.nextInt(); // perform a calculation and display the result double total = price * quantity; System.out.println(); System.out.println(quantity + " " + productCode

  • " @ " + price + " = " + total); System.out.println();

Relational operators (for comparison not for assignment)

Operator Name Returns a true value if…

== Equality Both operands are equal.

!= Inequality The left and right operands are not

equal.

> Greater Than The left operand is greater than the

right operand.

Less Than The left operand is less than the

right operand.

Greater Than Or

Equal

The left operand is greater than or

equal to the right operand.

Less Than Or

Equal

The left operand is less than or

equal to the right operand.

Two methods of the String class

Method Description

equals(String) Compares the value of the String object

with a String argument and returns a true

value if they are equal. Comparison is case-

sensitive.

equalsIgnoreCase(String) Works like the equals method but is not

case-sensitive.

Examples

userEntry.equals("Y") // equal to a string literal userEntry.equalsIgnoreCase("Y") // equal to a string literal (!lastName.equals("Jones")) // not equal to a string literal // equal to another string variable code.equalsIgnoreCase(productCode)

The syntax of the if/else statement if (booleanExpression) {statements} [else if (booleanExpression) {statements}] ... [else {statements}] How to code if/else statements  An if/else statement , or just if statement , always contains an if clause. It can also contain one or more else if clauses, and a final else clause.  If a clause requires more than one statement, you enclose the block of statements in braces. Otherwise, the braces are optional.  Any variables that are declared within a block have block scope so they can only be used within that block.

An if statement with else if and else clauses

if (customerType.equals("T"))

discountPercent = .4;

else if (customerType.equals("C"))

discountPercent = .2;

else if (subtotal >= 100)

discountPercent = .2;

else

discountPercent = .1;

What is the discountPercent when

 customerType is C and subtotal is 200

 subtotal is 5 0

 customerType is A and subtotal is 200

A loop that continues while choice is “y” or “Y” String choice = "y"; while (choice.equalsIgnoreCase("y")) { // get the invoice subtotal from the user Scanner sc = new Scanner(System.in); System.out.print("Enter subtotal: "); double subtotal = sc.nextDouble(); // see if the user wants to continue System.out.print("Continue? (y/n): "); // what if you forget to reset the value for choice? choice = sc.next(); System.out.println(); }