The correct choice is B. String phrase = sc.nextLine();
The nextLine() method of the Scanner class retrieves the entire line of input, including any whitespace such as spaces. The other choices would either not compile (C and D) or retrieve only part of the input (A and E).
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
Exam Objective 4.2 Given an algorithm as pseudo-code, determine the correct scope for a variable used in the algorithm and develop code to declare variables in any of the following scopes: instance variable, method parameter, and local variable.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
Chapter 5:Understanding Variable Scope and Class ConstructionIt Academy
Exam Objective 4.2 Given an algorithm as pseudo-code, determine the correct scope for a variable used in the algorithm and develop code to declare variables in any of the following scopes: instance variable, method parameter, and local variable.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
In this lecture we will discuss about another flow control method – Loop control.
A loop control is used to execute a set of commands repeatedly
The set of commands is called the body of the loop
MATLAB has two loop control techniques
Counted loops - executes commands a specified number of times
Conditional loops - executes commands as long as a specified expression is true
Java if else condition - powerpoint persentationManeesha Caldera
Conditions are one of a major feature in any programming language. This slide deck is discussing how to work with java conditions by using if else statement. Further discussing extends of if else statement.
The control statements enable us to specify the order in which the various instructions in a program are to be executed by the computer. They determine the flow of control in a program.
There are 4 types of control statements in C. They are:
a) Sequence control statements
b) Decision control statements or conditional statement
c) Case-control statements
d) Repetition or loop control statements
Programming in Java: Control Flow. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Java is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
In this lecture we will discuss about another flow control method – Loop control.
A loop control is used to execute a set of commands repeatedly
The set of commands is called the body of the loop
MATLAB has two loop control techniques
Counted loops - executes commands a specified number of times
Conditional loops - executes commands as long as a specified expression is true
Java if else condition - powerpoint persentationManeesha Caldera
Conditions are one of a major feature in any programming language. This slide deck is discussing how to work with java conditions by using if else statement. Further discussing extends of if else statement.
The control statements enable us to specify the order in which the various instructions in a program are to be executed by the computer. They determine the flow of control in a program.
There are 4 types of control statements in C. They are:
a) Sequence control statements
b) Decision control statements or conditional statement
c) Case-control statements
d) Repetition or loop control statements
Programming in Java: Control Flow. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
This course provides a strong background about JAVA programming language in the field of computing. The course begins with an introductory overview of the Computer and programs, with distinguishes the terms API, IDE and JDK, and gives a comprehensive knowledge about Java development kits and Java integrative development environments like eclipse and NetBeans. Furthermore, the course prepares student to write, compile, run and develop Java applications which are used to find out the solution for several real life problems, in conjunction with using GUI to obtain input, process and display outputs like message dialog boxes, input dialog boxes, confirmation dialog and so on.
JAVA is a computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The aim of this course is to explore Java programming fundamentals related to write, compile, run and develop Java applications that are used to discover the solution for several real life problems.
The official learning outcome for this course is: Upon successful completion of the course the students:
• Must know the basic concepts related JAVA programming language.
• Must know how to write, compile, run and develop java applications.
A combination of lectures and practical sessions will be used in this course in order to achieve the aim of the course.
By MSc. Karwan Mustafa Kareem
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2. BYTE FROM COMPUTING HISTORY
Alan Turing, also known as the father of
modern computing was a brilliant
mathematician and logician. He
developed the idea of the modern
computer and artificial intelligence.
Read about the Turing Machine.
2
3. GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• New data types
• Conditional branching
• Math methods and operators
3
4. LET’S DO SOME REVIEW
Website Java Visualizer:
https://cscircles.cemc.uwaterloo.ca/java_visualize/
Look at Basic Examples:
4
5. CLICKER QUESTION #1
REVIEW COMPOUND OPERATORS
What is the value of numCalories after executing
numCalories = 7;
numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5;
D. Same as numCalories = 7 + 5;
5
6. CLICKER QUESTION #1 ANSWER
6
zyBooks 2.6 Shorthand way to update a variable.
E.g. userAge++ or userAge += 1 is shorthand for
userAge = userAge + 1
Others -=, *=, /=, and %=.
What is the value of numCalories after executing
numCalories = 7; numCalories += 5;
Select the incorrect answer
A. Same as numCalories = numCalories + 5;
B. Same as numCalories = 12;
C. Same as numCalories = 5; incorrect
D. Same as numCalories = 7 + 5;
7. CLICKER # 2 REVIEW: INSTANTIATING CLASS
Select the statement below that declares a variable named myCalculator
and assigns to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator;
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;
D. myCalculator = new SalaryCalculator(); 7
8. CLICKER # 2 ANSWER
Select the statement below that declares a variable named myCalculator and assigns
to it a new object of type SalaryCalculator.
A. SalaryCalculator myCalculator; declares but does not assigns
B. SalaryCalculator myCalculator = new
SalaryCalculator();
C. SalaryCalculator = new SalaryCalculator;missing ()
D. myCalculator = new SalaryCalculator();missing class type 8
9. CLICKER QUESTION #3 REVIEW METHOD CALLS
9
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6
B. 12
C. 0
D. 18
10. CLICKER QUESTION #3 ANSWER
10
If the program prints 6 when line 6 is executed, what would the
following statement print?
System.out.println(yourTopping.getSize());
A. 6 size of cheese pizza
B. 12 correct
C. 0 incorrect answer
D. 18 incorrect answer
11. EXPLANATION CLICKER QUESTION #3
There are 2 constructors.
public Pizza(int size){...}
public Pizza(int size, String type){...}
11
12. DATA TYPES IN JAVA
• Data is represented as “types” in programming.
• In Java, a data type is defined as a primitive or a class.
• “Primitive” Data types and their values:
•Numeric: int, whole numbers, 2, 400, -99
double, fractional numbers, 7.34, 8.01,
-100.00
•Character: char, alpha-numeric symbols, ‘a’, ‘G’, ‘&’ , ‘}’, ‘9’
(notice 9 is not a number but character 9).
•Boolean: boolean, true or false (these values are
keywords). 12
13. RELATIONAL OPERATORS
Check conditions: Result of boolean type: true or false
13
Two sides of a
relational operator
have to be
compatible types.
Note:
==
!=
14. CONDITIONAL IF-ELSE
14
if (<some boolean test>)
do something;
if (<some boolean test>)
{ do a bunch of things;}
if (<some boolean test>)
{do a bunch of things;}
else
{do a bunch of other things;}
If no curly braces, only the first line after the if statement is executed.
<
>
<=
>=
Relational operators
Boolean evaluates to
TRUE / FALSE
15. CONDITIONALS - STYLE 1
15
if (x > 0) {
System.out.println("x is positive");
}
else if (x < 0) {
System.out.println("x is negative");
}
else {
System.out.println("x is zero");
}
What is the answer if x = -2? See Demo from Java Visualizer:
ControlFlow
16. 16
if (x == 0) {
System.out.println("x is zero");
}
else {
if (x > 0) {
System.out.println("x is positive");
}
else {
System.out.println("x is negative");
}
}
CONDITIONALS - STYLE 2
17. USE OF CONDITIONALS
17
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer");
int number = scan.nextInt();
if (number < 0)
System.out.println("Number entered isn't positive");
if (number > 0)
System.out.println(number + " is positive");
else
System.out.println(number + " is negative or zero");
Use conditionals for
user error checks!
18. A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
CLICKER QUESTION #4
18
int x = 5;
if (x > 0){
System.out.println("x is positive");
}
System.out.println("x is not zero");
What is printed?
19. A. x is positive
B. x is not zero
C. x is positive
x is not zero
D. Error
int x = 5;
if (x > 0)
{System.out.println("x is positive")};
System.out.println("x is not zero");
CLICKER QUESTION # 4 ANSWER
19
{Scope of if statement}
20. 20
• +, -, * behave in standard way.
• Division / is different
• In the absence of parentheses,
*, /, have higher precedence than +, -
• So: (3 + 5 * 2)is 13
(7 - 4 / 2) is 5
JAVA ARITHMETIC OPERATORS
5/3
1
5.0/3
1.6666666666666667
5/3.0
1.6666666666666667
See Demo from Java Visualizer:
CmdLineArgs
21. 21
Modulo mod operator %
With integers:
Gives integer remainder after repeated divisions of the
number by the modulus:
number % modulus
10 % 7 is 3
21 % 7 is 0
53 % 7 is 4
JAVA ARITHMETIC OPERATORS
22. 22
1. * / % have higher priority and performed first.
2. For same priority, operators are applied from left to
right.
3. Integer division always rounds towards zero.
4. When one or more operands are double, Java
performs “floating-point” division.
Check the Java™ Tutorials:
https://docs.oracle.com/javase/tutorial/java/nutsandb
olts/datatypes.html
KEEP IN MIND
23. MATH OPERATOR RULES
• Dividing by zero gives error
Exception in thread "main"
java.lang.ArithmeticException: / by zero
• int-to-double conversion is automatic but
double-to-int conversion may lose precision.
• Use type casting to convert a value of one type to another
type. e.g.
myIntVar = (int)myDoubleVar
myDoubleVar = (double)myIntVar
23
24. CLICKER QUESTION # 5
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
24
25. CLICKER QUESTION #ANSWER
NOTE:
JAVA converts from int
to double automatically
so 5.0 assigned to
num2.
25
int num1 = 5.1;
double num2 = 5;
What are the values?
A. num1 has value 5.1; num2 has value 5
B. num1 has value 5; num2 has value 5.0
C. num1 has value 5; num2 has value 5
D. Error: incompatible types
26. MATH METHODS - EXAMPLE
https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html 26
Static method: Independent of class object
27. REVIEW: METHODS AND PARAMETERS
Parameters refers to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method
is invoked.
When you invoke a method, the arguments used must match the
declaration's parameters in type and order. 27
double r = Math.max(3.5, 7.1);
ArgumentsReturn
From the
Java API,
Math class
max method
summary.Parameters
28. MATH METHOD EXAMPLES
28
double r = Math.max(3.5, 7.1); //7.1
double s = Math.sqrt(2.0);
//1.4142135623730951
double t = Math.sin(.7); //0.644217687237691
double u = Math.min(3.5, 7.1); //3.5
double v = Math.pow(2,5); //32.0
30. STRATEGIES FOR DEBUGGING
1. Set a breakpoint prior to the line of code where you
think the problem occurs.
2. When the program gets to the breakpoint, inspect the
variables for correct values.
3. Correct the error and repeat till the program runs
correctly.
30
31. TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
31
33. GOALS FOR TODAY’S CLASS
You are now familiar with Objects and Classes and
writing programs to solve a problem.
We now work with the “building blocks” or syntax of
the Java programming language:
• Review conditional statements
• The Random method
• Characters & Strings
2
34. REVIEW: CONDITIONAL IF STATEMENTS
First evaluate (alpha > beta):
(2 > 1) TRUE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is TRUE so we
execute the true branch:
eta = alpha + 2 = 2 + 2 = 4
gamma = alpha + 5 = 2 + 5 = 7
3
int alpha = 2, beta = 1,
delta = 3, eta = 0, gamma = 0;
35. Think - Pair -Share
4
int alpha = 2;
int beta = 1,
int delta = 3,
int eta = 0,
int gamma = 0;
Evaluate these
statements and
determine the value of all
variables used.
36. EXPLANATION
For if statement, determine whether
true or false
First we evaluate (alpha > delta):
(2 > 3) FALSE
If true – follow true branch, if false –
do nothing or follow else branch
The condition is FALSE so we follow
the else branch.
gamma = beta + 5 = 1 + 5 = 6
Next sequential statement is always
executed:
eta = beta + 2 = 1 + 2 = 3
5
37. CLICKER QUESTION 1
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2; 6
Evaluate the statements and
determine the value of eta
given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa
= 3.0;
A. 2
B. 3
C. 4
D. 5
38. CLICKER QUESTION 1 ANSWER
if (omega > kappa)
{
if (alpha > delta)
eta = 5;
else
eta = 4;
}
else
if (alpha < delta)
eta = 3;
else
eta = 2;
7
Evaluate the statements and
determine the value of eta given:
int alpha = 2, delta = 3,
eta = 0;
double omega = 2.5, kappa =
3.0;
A. 2
B. 3
C. 4
D. 5
FALSE
TRUE
39. To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns a random
number
8
call nextInt()
method
Import statement
New instance
40. To generate random numbers- e.g., to simulate real-world
situation, gaming, etc. see DiceRoll.java
THE RANDOM CLASS
Returns 10 possible values from 0 to 9 9
41. 10
OTHER USES OF nextInt METHOD
Generates any 6 values starting at 10.
42. 11
OTHER USES OF nextInt METHOD
With a specific seed, each program run will yield the same
sequence of pseudo-random numbers.
Set the seed
declare int variable
43. CLICKER QUESTION #2
Which of the following will work like flipping a coin
and getting us 0 and 1 (heads/tail)?
A. randGen.nextInt(0);
B. randGen.nextInt(1);
C. randGen.nextInt(2);
D. randGen.nextInt(3);
12
44. CLICKER QUESTION #2 ANSWER
Which of the following will work like flipping a coin?
A. randGen.nextInt(0);
Error: bound must be positive
B. randGen.nextInt(1);
Gives 0;
C. randGen.nextInt(2);
Gives 0/1 (heads/tails)
D. randGen.nextInt(3);
Gives 0, 1, or 2 13
48. IDENTITY vs EQUALITY (STRINGS)
== tests identity
input1==input2
false!
== is not true here (different objects)
"bye"
:String
"bye"
:String
input1
== ?
input2
String input1 = new String(”bye");
String input2 = new String(”bye");
17
49. IDENTITY VS EQUALITY (STRINGS)
equals tests equalityinput1.equals(input2)
TRUE!
Only use "==" to test if whole numbers or characters
are equal. For String use the method equals
"bye"
:String
input1
"bye"
:String
equals ?
input2
18
50. EQUALITY OPERATORS: SUMMARY
Checks whether two operands' values are the same
(==) or different (!=).
Evaluates to a Boolean value: TRUE or FALSE.
Also useful for checking expressions e.g.
19
51. CLICKER QUESTION #3
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
20
52. CLICKER QUESTION #3 ANSWER
String name1 = "Grace Hopper";
String name2 = new String("Grace Hopper");
Evaluate: name1 == name2
A. True
B. False
C. Maybe
D. Don’t know
Evaluate:
name1.equals(
name2)
Ans: TRUE
21
53. Scanner console = new Scanner(System.in);
Scanner object means: input from keyboard
console.nextInt()--- looking for int value
console.nextDouble()--- looking for double value
console.next() --- looking for String value
console.nextLine() --- looking for a whole line
https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html
REVIEW: SCANNER CLASS METHODS
22
54. CLICKER QUESTION #4
A. String phrase = sc.nextInt();
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase;
D. String phrase = sc.nextLine;
E. String phrase = sc.nextString();
Scanner sc = new Scanner(System.in);
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
23
55. CLICKER QUESTION #4ANSWER
A. String phrase = sc.nextInt(); For ints
B. String phrase = sc.nextLine();
C. String phrase = sc.nextPhrase; No such method
D. String phrase = sc.nextLine; Missing ()
E. String phrase = sc.nextString(); No such
method
Scanner sc = new Scanner(System.in);
System.out.println(”Enter first phrase");
Which choice retrieves all that is typed?
24
56. TO-DO
• Check your iClicker grades in Moodle.
• Study zyBook chapter 1-3 (content for exam)
• Communicate with us using only Moodle forum or
Piazza.
• Start Project 2 early - seek help in office hours.
• Start zyBooks chapter 4 exercises.
• Read ALL the exam instructions sent to
you.
25