27
Lecture#4 Aleeha Iftikhar

130706266060138191

Embed Size (px)

Citation preview

Lecture#4Aleeha Iftikhar

Accepting Input from a Userimport java.util.Scanner;public class StringVariables {

public static void main (String args[]){Scanner new_object = new

Scanner( System.in ); String first_name;System.out.print("Enter your first name: ");first_name = new_object.next( );

String family_name;System.out.print("Enter your family name:

");family_name = new_object.next( );

String full_name;full_name = first_name + " " +

family_name;System.out.println("You are " + full_name);}}

• Scanner class is use to handles input from a user .

• It can be found in the java.util library.

• A class is just a bunch of code. It doesn't do anything until you create a new object from it.(new_object).

• Tell java that this will be System Input (System.in).

• gets the next string of text that a user types on the keyboard( next() ).

• println will move the cursor to a new line after the output, but print stays on the same line.

Java Option Panesimport javax.swing.JOptionPane;public class Messageboxes {

public static void main (String args[]){String first_name;first_name =

JOptionPane.showInputDialog("First Name");

String family_name;family_name =

JOptionPane.showInputDialog("Family Name");

String full_name;full_name = "You are " + first_name + " " +

family_name;

JOptionPane.showMessageDialog( null, full_name);

System.exit(0);

}}

• JOptionPane class is use for accepting user input, and displaying results.

• This is located in the javax.swing library.

• The JOptionPane class allows you to have input boxes and message boxes.

• the showInputDialog method of JOptionPane class is used to get an input box that the user can type into.

• showMessageDialog is use to display the result in a message box.

• Null tells that the message box is not associated with anything else in the programme.

Control Statements

Selection StatementsUsing if and if...elseNested if StatementsUsing switch StatementsConditional OperatorBoolean OperatorsRepetition StatementsLooping: while, do-while, and forNested loopsUsing break and continue

if Statementsif (booleanExpression) { statement(s);}Example:if ((i > 0) && (i < 10)) { System.out.println("i is an " + "integer between 0 and 10");}

if ( testScore >= 95 )

System.out.println("You are an honor student");Then BlockThen Block

Boolean ExpressionBoolean Expression

Control Flow of iftestScore >= 95?

testScore >= 95?

falseSystem.out.println ( "You are an honor student");

System.out.println ( "You are an honor student");

true

The if...else Statement

if ( testScore < 70 )

System.out.println("You did not pass");

else

System.out.println("You did pass ");

if ( <boolean expression> )

<then block>

else

<else block>

Then BlockThen Block

Else BlockElse Block

Compound Statements

Use braces if the <then> or <else> block has multiple statements.

if (testScore < 70)

{

System.out.println("You did not pass“ );

System.out.println(“Try harder next time“ );

}

else

{

System.out.println(“You did pass“ );

System.out.println(“Keep up the good work“ );

}

Then BlockThen Block

Else BlockElse Block

Exampleif (radius >= 0) { area = radius*radius*PI;

System.out.println("The area for the “ + “circle of radius " + radius + " is " + area);}else { System.out.println("Negative input");}

Control Flow

System.out.println("You did pass");

System.out.println("You did pass");

falsetestScore < 70 ?

testScore < 70 ?

System.out.println("You did not pass");

System.out.println("You did not pass");

true

The Nested-if Statement

An if statement containing another if statement is called a nested-if statement.

if (testScore >= 70) {

if (studentAge < 10)

{

System.out.println("You did a great job");

}

else {

System.out.println("You did pass"); //test score >= 70

} //and age >= 10

}

else

{ //test score < 70

System.out.println("You did not pass");

}

Control Flow of Nested-if Statement

System.out.println("You did not pass");

System.out.println("You did not pass");

false

System.out.println("You did pass");

System.out.println("You did pass");

false

testScore >= 70 ?testScore >= 70 ?

true

studentAge < 10 ?studentAge < 10 ?

System.out.println("You did a great job");

System.out.println("You did a great job");

true

Exampleif (num1 < 0)

if (num2 < 0)

if (num3 < 0)

negativeCount = 3;

else

negativeCount = 2;

else

if (num3 < 0)

negativeCount = 2;

else

negativeCount = 1;

else

if (num2 < 0)

if (num3 < 0)

negativeCount = 2;

else

negativeCount = 1;

else

if (num3 < 0)

negativeCount = 1;

else

negativeCount = 0;

if – else if Control

if (score >= 90)

System.out.print("Your grade is A");

else if (score >= 80)

System.out.print("Your grade is B");

else if (score >= 70)

System.out.print("Your grade is C");

else if (score >= 60)

System.out.print("Your grade is D");

else

System.out.print("Your grade is F");

Test Score Grade90 score A

80 score 90 B

70 score 80 C

60 score 70 D

score 60 F

switch StatementsSyntax for the switch Statementswitch ( <arithmetic expression> ) {

<case label 1> : <case body 1>

<case label n> : <case body n>

}

switch ( gradeLevel ) {

case 1: System.out.print( "Go to the Gymnasium" );

break;

case 2: System.out.print( "Go to the Science Auditorium" );

break;

case 3: System.out.print( "Go to Harris Hall Rm A3" );

break;

case 4: System.out.print( "Go to Bolt Hall Rm 101" );

break;

}

Case Body

Case Body

Arithmetic ExpressionArithmetic Expression

Case Label

Case Label

The switch Statement ExampleScanner scanner = new Scanner(System.in);

System.out.println( "Grade (Frosh-1,Soph-2,...):“); int gradeLevel = scanner.nextInt();

switch (gradeLevel) {

case 1: System.out.print("Go to the Gymnasium");

break;

case 2: System.out.print("Go to the Science Auditorium");

break;

case 3: System.out.print("Go to Harris Hall Rm A3");

break;

case 4: System.out.print("Go to Bolt Hall Rm 101");

break;

}

This statement is executed if the gradeLevel is equal to 1.

This statement is executed if the gradeLevel is equal to 1.

This statement is executed if the gradeLevel is equal to 4.

This statement is executed if the gradeLevel is equal to 4.

switch With No break Statements

x = 10;x = 10;N == 1 ?

N == 1 ?

x = 20;x = 20;

x = 30;x = 30;

N == 2 ?

N == 2 ?

N == 3 ?

N == 3 ?

switch ( N ) {

case 1: x = 10;

case 2: x = 20;

case 3: x = 30;

}

switch With break Statements

switch ( N ) {

case 1: x = 10;

break;

case 2: x = 20;

break;

case 3: x = 30;

break;

}

x = 10;x = 10;

false

trueN == 1 ?

N == 1 ?

x = 20;x = 20;

x = 30;x = 30;

N == 2 ?

N == 2 ?

N == 3 ?

N == 3 ?

false

false

true

true

break;break;

break;break;

break;break;

switch With the default Block

switch (ranking) {

case 10:

case 9:

case 8: System.out.print("Master");

break;

case 7:

case 6: System.out.print("Journeyman");

break;

case 5:

case 4: System.out.print("Apprentice");

break;

default: System.out.print("Input error: Invalid Data");

break;

}

switch Statement RulesThe switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses.

The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. (The case statements are executed in sequential order.)

The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.The default case, which is optional, can be used to perform actions when none of the specified cases is true. ·       The order of the cases (including the default case) does not matter. However, it is a good programming style to follow the logical sequence of the cases and place the default case at the end.

CautionDo not forget to use a break statement when one is needed. For example, the following code always displays Wrong number of years regardless of what numOfYears is. Suppose the numOfYears is 15. The statement annualInterestRate = 8.50 is executed, then the statement annualInterestRate = 9.0, and finally the statement System.out.println("Wrong number of years").

switch (numOfYears) { case 7: annualInterestRate = 7.25; case 15: annualInterestRate = 8.50; case 30: annualInterestRate = 9.0; default: System.out.println("Wrong number of years");}

Boolean or logical Operators• A boolean operator takes boolean values as

its operands and returns a boolean value. • The three boolean operators are

– and: &&– or: ||– not !

if (temperature >= 65 && distanceToDestination < 2) {System.out.println("Let's walk");

} else {System.out.println("Let's drive");

}

Semantics of Boolean Operators

• Boolean operators and their meanings:

P Q P && Q P || Q !P

false false false false true

false true false true true

true false false true false

true true true true false

Boolean ValuesA Boolean value is one with two choices: true or false, yes or

no, 1 or 0. In Java, there is a variable type for Boolean values:boolean user = true;So instead of typing int or double or string, you just type

boolean (with a lower case "b"). After the name of you variable, you can assign a value of either true or false.

Notice that the assignment operator is a single equals sign ( = ). If you want to check if a variable "has a value of" something, you need two equal signs ( = =).

boolean x = true;if ( x == true) {

System.out.println("it's true");}else {System.out.println("it's false");}

Conditional OperatorThere a three type of operators based on operands used, namely unary,binary, ternary.

Unary - This works with one operand (e.g: a++, a will be incremented by 1),

Binary - This works with two operands (e.g: a+b), Ternary - This works with three operands (e.g: condition? value 1 :

value 2).

Ternary operator or conditional operator There is only one ternary operator, which is the ?: conditional operator

that uses three operands(booleanExp) ? exp1 : exp2

if (x > 0) y = 1else y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;

Conditional Operatorif (num % 2 == 0) System.out.println(num + “is even”);else System.out.println(num + “is odd”);

System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);

THE END