CS 145 Lecture 21 – Loops Cont’d
Dear students,
Let’s start with a little Program This:
Write a methodindexOf
that accepts aString
and achar
as parameters. Without using the builtinString.indexOf
method, it returns the index at which the given character resides in theString
. If no such character can be found, return -1.
Then, let’s seem some more example of loops:
- Write
lastIndexOf
. - Write a routine that supports fill-down behavior as seen in a spreadsheet.
- Write a text-based spinner/beach-ball/progress wheel.
- Write a random spelunking workout.
- Program this.
Before we meet again, please do the following:
- Start homework 4, which is worth 10 blugolds. It’s due before November 11.
- Lab 7 is posted. You are welcome to start early.
See you next class!
Sincerely,
P.S. It’s Haiku Friday!
They don’t go crazy
So why’d Robot cross the road?
Chicken programmed it
P.P.S. Here’s the code we wrote together…
BradBrad.java
package lecture1028; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class BradBrad { public static void main(String[] args) throws IOException { BufferedImage image = new BufferedImage(512, 256, BufferedImage.TYPE_INT_RGB); Color color = new Color(0, 255, 255); image.setRGB(100, 100, color.getRGB()); ImageIO.write(image, "png", new File("/Users/johnch/Desktop/image.png")); } }
Stringing.java
package lecture1028; public class Stringing { public static void main(String[] args) { String s = "Abraham"; System.out.println(indexOf(s, 'm')); System.out.println(indexOf(s, 'a')); System.out.println(lastIndexOf(s, 'a')); } public static int indexOf(String s, char c) { for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == c) { return i; } } return -1; } public static int lastIndexOf(String s, char c) { for (int i = s.length() - 1; i >= 0; --i) { if (s.charAt(i) == c) { return i; } } return -1; } }
Chess.java
package lecture1028; public class Chess { public static void main(String[] args) { // For each row for (int r = 1; r <= 8; r++) { // For each column for (int c = 1; c <= 8; c++) { System.out.printf("%3d", r * c); } System.out.println(); } } }