Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

CSBP219_SP25_Java_Week2

The document covers the basics of Java, focusing on input/output operations, including console and file I/O, as well as formatting output using methods like printf. It also introduces control structures such as if statements, switch cases, and string comparisons. Key concepts include using the Scanner class for input and PrintWriter for output, along with relational and logical operators.

Uploaded by

banana80milk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CSBP219_SP25_Java_Week2

The document covers the basics of Java, focusing on input/output operations, including console and file I/O, as well as formatting output using methods like printf. It also introduces control structures such as if statements, switch cases, and string comparisons. Key concepts include using the Scanner class for input and PrintWriter for output, along with relational and logical operators.

Uploaded by

banana80milk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Week 2‐Part 1

Basics of Java
Reading and Writing from Keyboard and Files (I/O events).
Objectives
 Output Results to Console
 Formatted output with printf method
 Input data into memory using input statements
 Input & output dialog boxes
 File input & output

2
Output
Output on the standard output device is accomplished by using the
standard output object System.out

print leaves the insertion point after the last character of the value of the
expression.
println positions the insertion point at the beginning of the new line.
Slide 3

3
Output
Exercises: what is the output of the following program?

public class PrintTest {


public static void main(String[] args) {
System.out.println("A");
System.out.println();
System.out.print("B");
System.out.println("C");
System.out.print("D");
System.out.print(" ");
System.out.println("E");
Slide 4

}
}

4
Output

\n Newline Cursor moves to the beginning of the next line


\t Tab Cursor moves to the next tab stop
\b Backspace Cursor moves one space to the left
\r Return Cursor moves to the beginning of current line
\\ Backslash Backslash is printed
\’ Single quotation Single quotation mark is printed
\’’ Double quotation Double quotation mark is printed
Slide 5

5
Output
Exercises: what is the output of the following program?
Slide 6

6
Formatting Output with printf
 Standard output object System.out has two methods:
 print()
 println()
 To output the results, the following statement is used:

 Methods print() & println() cannot directly format


certain outputs in a specific manner:
 default output of floating‐point numbers is up to 6 or 15
decimal places

7
Formatting Output with printf
 To format the output in specific manner, method printf() is used:

OR

 formatString: a string specifying the format of the output


 argumentList: a list of arguments –constants, values or expressions
 Example

System.out.printf("There are %.2f inches in %d centimeters.",


centimeters / 2.54, centimeters);

8
printf Method
 Formatting the output can be done using the printf
method :

Example:
public class PrintFormat {
public static void main (String [] args) {
double x = 1234.23456789;
int num = 12342345;
System.out.printf(“%.2f”, x);
System.out.println();
System.out.printf(“%.3f”, x);
System.out.println();
System.out.printf(“%10d”, num);
System.out.println();
System.out.printf(“%5d%7.2f”, num, x);
System.out.println();
}
} 9
String Method format
 Formatting the output can be done using the String
method format:

Example:

10
Input (Read) Statement
Data can be put into variables from the standard input device(keyboard)
using the input statement of Java.
Java provides the class Scanner.
Using Scanner class, an input stream object is created, and it is
associated with the standard input device:

Scanner console = new Scanner(System.in);


Slide 11

11
Input (Read) Statement
The object console reads the next input as follows:
The expression console.nextInt() retrieves the next input as an integer.
The expression console.nextDouble() retrieves the next input as a
floating‐point number.
The expression console.next() retrieves the next input as a string.
The expression console.nextLine() retrieves the next input as a string
until the end of the line.
The expression console.next().charAt(0) retrieves the next input as a
single printable character.
Slide 12

12
Input (Read) Statement
Example:
Slide 13

13
File Input / Output
 Getting input from keyboard and sending output to the
screen have limitations.
 If the amount of input data is large:
 inefficient: to type it takes a large amount of time
 inconvenient: to type it can generate errors
 Solution: file input & output
 File: an area in secondary storage used to hold
information

14
File Input / Output
 To input a file, a Scannerobject is initialized with a FileReader
object:

 To store the output of a program in a file, class PrintWriter is


used:

 To close the input & output files, the method close is used:

inputFile.close();
outFile.close();

15
File Input / Output
Summary:
 Read from File:
 FileReader
 replace System.in

 add exception

 Create the file // MUST


 Close the file //Optional

 Read from File:


 PrintWriter
 add exception
 Replace System.out
 Create the file // Optional
 Close the file // Must

16
File Input / Output
 Example:

17
File Input / Output
Console Input/Output File Input/Output

18
Week 2 – Part 2
Basics of Java
Control Structure – Selection
Objectives
 In this chapter you will learn:
 Control structures
 Relational & logic operators
 Logic (boolean) expressions
 if , if…else
 switch
 String comparison

20
Relational Operators

Operator Description
== Equal to
!= Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

21
Logical (Boolean) Operators &
Expressions
 Logical (Boolean) Operators & Expressions

Operator Description
! Not
&& And
|| Or

22
Conditional Expressions
Scanner console = new Scanner(System.in);
int score = console.nextInt();
 if String grade = "";

if(score >= 90)


grade = "A";
if(score < 90 && score >= 80)
grade = "B";

 if … else double rate = console.nextDouble();


int hours = console.nextInt();
double wages;

if (hours <= 40)


wages = rate * hours;
else
wages = (rate * 40) + 1.5 * (rate * (hours ‐40));
23
Conditional Expressions

 if … else if … else
Scanner console = new Scanner(System.in);
int score = console.nextInt();
String grade = "";

if( score >= 90)


grade = "A";
else if (score >= 80)
grade = "B";
else if (score >= 70)
grade = "C";
else if (score >= 60)
grade = "D";
else
grade = "F";

24
Conditional Operator (? :)
 Certain if… else statements can be written more
concisely by using the conditional operator: ? :
 ? : is a ternary operator:

 If expression1 is true, the result of the conditional expression is expression2;


otherwise the result is expression3

25
switch Structures
 A case value must appear only once.
 One or more statements may follow
case label, you do not need to use
braces.
 The break statement may or may not
appear after case statements.
 A switch structure may or may not
have the default label.

26
switch Structures
 Example:
Scanner console = new Scanner(System.in);
String month = console.next(); // “Abc”
switch(month) {
case “Jan”:
Scanner console = new Scanner(System.in); case “Mar”:
char grade = console.next().charAt(0); case “May”:
case “Jul”:
switch(grade) { case “Aug”:
case “Oct”:
case ‘A’: case “Dec”:
System.out.println(“The grade is A.”); System.out.println(“31 Days.”);
break; break;
case ‘B’: case “Apr”:
System.out.println(“The grade is B.”); case “Jun”:
break; case “Sep”:
case ‘C’: case “Nov”:
System.out.println(“The grade is C.”); System.out.println(“30 Days.”);
break; break;
default: break; case “Feb”:
} System.out.println(“28 or 29 Days.”);
break;
default:
System.out.println(“Wrong Month”);
}

27
String Comparisons

 Compare the values of String objects: strings are


compared character by character, starting with the first
character:
1. equals method
2. compareTo method

 Compare the values of the String variables: strings are


compared to determine if they reference the same String
object:
1. ==
2. !=

28
String Comparisons
 Strings are compared character by character, starting
with the first character.

 The character‐by‐character comparison continues until


one of the following three conditions met:
1. a mismatch is found
2. the last characters have been compared & are equal
3. one string is exhausted

29
equals Method

30
equals Method

31
compareTo Method

More than

32
compareTo Method

33
compareTo Method

34
Comparing String Variables
 The expression (str1 == str2) determines whether the
str1 and str2 reference (point to) the same object.
 The expression (str1 != str2) determines whether the
str1 and str2 do not reference (point to) the same
object.
 Example:

35
Comparing String Variables
 The expression (str1 == str2) determines whether the
str1 and str2 point to the same object.
 The expression (str1 != str2) determines whether the
str1 and str2 do not point to the same object.
 Example:

36
Comparing String Variables

37
Comparing String Variables
import java.util.*;

public class Main


{
public static void main(String[] args) {
Scanner user = new Scanner(System.in);

System.out.println("Enter two names: ");


String n1 = user.next(); //"Ali"
String n2 = user.next(); //"Ali"
String n3 = n1;

System.out.println("n1 == n2: " + (n1==n2)); //F


System.out.println("n1 == n3: " + (n1==n3)); //T

System.out.println("n1 equals n2: " + n1.equals(n2)); //T


System.out.println("n1 equals n3: " + n1.equals(n3)); //T
}
}
38

You might also like