CSCI1933 Lecture3
CSCI1933 Lecture3
• Today:
• Finish loops example, variable scope, strings,
string operations
• Announcements:
• Project 1 assigned (see Canvas); due 2/11
(before 7pm) Get started now!
• Lab 2 due this Friday (last office hours)
Brief review of key concepts covered last time
Variables in Java
• Variable declaration: necessary before the first use of a
variable—need to tell Java what types your variables are
so it knows how to store them in memory, what are the
possible operations
o Assignment statements: ‘=’ operator
o Initialization: always initialize, either when you
declare or when you use
o Examples:
o Name joe = new Name();
o int k=10;
Two variable types in Java
• Reference variables: Class types, either defined by
you or using the Java built-in classes
• Primitive variables:
int, char, float, double, boolean, long,
short, byte
Once you know how to use a Scanner object, you know how to do both!
Conditionals example #1
Comments: always use parentheses to group when in doubt! Good idea to keep statements as simple
as possible
Loops
• Loops are one of the most useful and
important constructs in most languages: they
enable repetition
Example:
Output:
What’s1the output?
2
int number = 10; 3
int count = 1; 4
while (count <= number) 5
{ 6
System.out.println(count); 7
count++; 8
} // end while 9
10
Note: for while loops, we typically need to include an increment statement at the end
(count++) to move the loop along.
While loops
• Basic structure:
<initialization statements>
while( <boolean expression> ) {
<loop body: block of statements>
}
Example:
Output:
1
2
int number = 10; 3
int count = 1; 4
while (count <= number) 5
{ 6
System.out.println(count); 7
count++; 8
} // end while 9
10
Note: for while loops, we typically need to include an increment statement at the end
(count++) to move the loop along.
The “do-while” loop
Basic structure:
do
{
<block of statements>
} while(<boolean expression>);
Example:
Example:
int count, number;
number = 10;
for (count=1; count <= number; count++) {
System.out.println(count);
}
• Main difference from while: initialization and update operations are built in to
loop construct
• Note initialize, test, update + syntax (no semi-colon after update)
For loops (2)
• Test condition and the update operation are
flexible, e.g. Output:
For:0
For:2
number = 10; For:4
for (count=0; count < number; count+=2) { For:6
What’s the output?
System.out.println(“For:”+count); For:8
}
Output:
number = 10; For:10
for (count=10; count > 0; count--) { For:9
System.out.println(“For:”+ count); For:8the output?
What’s
} For:7
For:6
For:5
For:4
For:3
For:2
For:1
For loops (2)
• Test condition and the update operation are
flexible, e.g. Output:
For:0
For:2
number = 10; For:4
for (count=0; count < number; count+=2) { For:6
System.out.println(“For:”+count); For:8
}
Output:
number = 10; For:10
for (count=10; count > 0; count--) { For:9
System.out.println(“For:”+ count); For:8
} For:7
For:6
For:5
For:4
For:3
For:2
For:1
New material
Overview of today’s material
See CondLoopDemo.java
Labeled “break” example
Note: break applies to
innermost loop unless you
label it otherwise
Other useful loop concepts
• “Continue” statement: loop skips to the next
iteration immediately upon encountering this
statement
Example:
int j,sum=0;
for(j =0; j < 20; j++) {
if(j%2 == 1) { continue; }
System.out.println("Adding "+j);
sum += j;
}
Note: continue applies to
What does this do? innermost loop unless you
label it otherwise
Note about break and continue
statements
• Use them carefully!
• They alter the normal execution of loops and
make your programs harder to interpret later
• Avoid using them if possible, but they can be
convenient in some cases
Nested loops
• Additional loops can be included inside blocks
of statements just like anything other
statements (“nested” loops)
int x = 50;
int y = 5;
Output:
**************************************************
**************************************************
**************************************************
**************************************************
**************************************************
Another nested loop example
System.out.print("\t");
for(i=1; i <= 8; i++) {
System.out.print(i+"\t");
}
System.out.println();
See CondLoopDemo.java
For practice: use loops to draw this
**
**** Triangle, base = 40, height =40
******
********
**********
************
**************
****************
******************
********************
**********************
************************
**************************
****************************
******************************
********************************
**********************************
************************************
**************************************
****************************************
**************************************
************************************
**********************************
********************************
******************************
****************************
**************************
************************
**********************
********************
******************
****************
**************
************
**********
********
******
****
***
Loop exercise
return result;
}
Reminders about solving problems
with recursion
Recursive solution: an operation that can be defined in
terms of itself
– Solving a problem using recursion depends on solving
smaller occurrences of the same problem
return result;
}
double result;
if(x <= 1) { result=1;}
else {
result = x*recurseFactorial(x-1);
}
return result;
}
Benchmarking the factorial implementations
int x=150;
int N=5000000;
}
int z = x*2; No!
double y = Math.sqrt(z); //is this ok?
}
Example from: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm
Variable declared within a statement block:
example #2
}
Main points:
• parameters passed into a method are visible throughout the method
• parameter variables are not visible in other methods of the class
Variable declared as parameter of a method or
constructor
public class MyMath {
return result;
}
Note that I can use “x” in two different methods, and they
have nothing to do with one another
Variable declared within a class definition as a
data member
public class MyMath {
private double x=100;
return result;
}
return result;
} What’s the output of this code?
Output: MyMath calculator = new MyMath();
} x:1.0 this.x=100.0 double result =
x:3.0 this.x=100.0 calculator.linearFunction(10,0,1);
result=10.0 System.out.println(“result=“+result);
Class data member example
public class MyMath {
private double count=0;
count++;
return result;
Code in main program:
} MyMath calculator = new MyMath();
calculator.linearFunction(10,0,1);
public double getNumCalls() { double sum=0;
return count; for(int i=1; i < 100; i++) {
} sum += calculator.factorial(i);
}
} System.out.println("NumCalls="+calculator.get
NumCalls());
Review of variable scope
System.out.println(className);
String example: comparison
Output:
Strings not equal!
Output:
Strings are equal!
Output:
Strings are equal!
(Also equalsIgnoreCase() method – treats upper and lower case the same)
Comparing strings (2)
• compareTo method
• compares two Strings to see which is alphabetically first
• returns an integer
• negative string you’re comparing is alphabetically before the
string passed
• positive string you’re comparing is alphabetically after the
string passed
• 0 the two Strings are equal
(Also compareToIgnoreCase() method – treats upper and lower case the same)
String concatenation
str1 = "string1";
str2 = "string2";
str1 += str2;
System.out.println("Concatenated strings:"+str1);
Searching within strings
• int indexOf(char c): finds first occurrence of character c
• Example:
String className = "UMN:CSCI:1933:Sec001";
StringTokenizer st = new Output:
StringTokenizer(className,":"); 1:UMN
2:CSCI
int count=1; 3:1933
while(st.hasMoreTokens()) {
4:Sec001
System.out.println(count+":"+st.nextToken());
count++;
}
String exercise #1
• Write a short program to reverse a string
called “revString”
Example:
int mondayTemperature=50;
int tuesdayTemperature=55;
int wednesdayTemperature=75;
int thursdayTemperature=45;
int fridayTemperature=40;
int saturdayTemperature=35;
int sundayTemperature=65;
vs.
int[] temperatures = {50,55,75,45,40,35,65};
Array declarations
• Declaration/initialization of arrays:
Primitives Arrays
Bracket notation:
int[] temperatures = new int[7];
temperatures[0] = 35;
Sometimes it’s useful to use variables as array indices:
int monday = 0;
temperatures[monday] = 35;
Indexing details
This is a good feature but tedious for most cases where arrays
are useful
Arrays exercise
Linear search
int[] a = new int[]{23, 565, 21, 56, 22,1000,675, 123, 676, 87};
Assignment operators
For array elements, "=" is a copy operation:
temperatures[monday] = temperatures[sunday];
Output:
Ashlee
Austin
String[] TAs ={“Ashlee",“Austin",“Alice",“Isaac"}; Alice
for (String curr : TAs) { Isaac
System.out.println(curr);
}
Output:
int[] intArray = {1,2,3,4}; 1
for(int curr : intArray) { 2
System.out.println(curr); 3
} 4
Passing arrays to functions
public static double calcMean(int[] a) {
double result=0;
return(result/a.length);
}
In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
System.out.println("Mean: "+calcMean(arr));
Passing arrays to functions (2)
public static void negateArray(int[] arr) {
for(int i=0; i < arr.length; i++) {
arr[i]=-arr[i];
}
In main program:
int arr[] = {10, 90, 49, 2, 1, 5, 23};
negateArray(arr);
System.out.println("Negated element: "+arr[0]);
return(newarr);
}
In main method:
int[] zeroArray = getZeros(10);
System.out.println("Length: "+zeroArray.length+",
first element: "+zeroArray[0]);
if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}
What’s wrong with this code?
if(keyboard.hasNextInt()) {
circleArray[count++] = new Circle(0,0,keyboard.nextInt());
} else { break; }
}
Throws ArrayIndexOutOfBoundsException!
if(keyboard.hasNextInt()) {
circleArray[count++] = new
Circle(0,0,keyboard.nextInt());
} else { break; }
}
Exercise: Write a function called resize that can compact our array
Resize function
• What is grades.length?
• How about grades[0].length?
(https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html )
Example: array operations
System.out.println("Original:");
System.out.println(Arrays.toString(numArray));
System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));
Example 2: array operations
int[] numArray = new int[100];
System.out.println("Original:");
System.out.println(Arrays.toString(numArray));
System.out.println("Sorted:");
Arrays.sort(numArray);
System.out.println(Arrays.toString(numArray));
if(result > 0) {
System.out.println("Found! Index:"+result);
} else {
System.out.println("Not found! Index:"+result);
}
Important reminders