1. Engineering
  2. Computer Science
  3. the goal of this assignment is to use loop patterns...

Question: the goal of this assignment is to use loop patterns...

Question details

The goal of this assignment is to use loop patterns to solve a variety of problems Starting 1. In Eclipse, create a new project or use an assignments one. Add a package a4, and a class SearchAndOptimizingLoops to that package. Copy and paste Picture.java and an image file from prior work into this package (Picture.java should update itself to the a4 package). 2. In your class, implement the static methods specified below 3. All methods you write should have a Javadoc comment with a description of what the method does and a @param for each parameter and a @return describing what information is returned 4. Add a main method with tests for each method. Your tests should cover possible return values (such as true or false) as well as special cases (for example, empty strings). Your tests should print what was expected as well as the actual result from the method in a neatly formatted way. 5. You do not need to test for cases that are prohibited in the description. If the description says that there is at least X in the parameter, then you do not need to test for the truth of that constraint 6. None of your methods except for main may print anything to the console. 7. Ensure you have consistent spacing and indenting in your file, proper and consistent indenting, and a Javadoc comment about the start of the class definition with your name, assignment number and class Required Methods You must implement each of the described methods with method name, return type and parameters carefully checked against the specification. When parameters are specified you must use the order they are listed in. You may implement additional methods if they aid your problem-solving 1. Method name: findSmallestPositiveNumber Parameter(s): A String containing integer numbers separated by spaces. There must be at least one positive number in the String. Return value: An int value that is the smallest number greater than O in the input string Example: findSmallestPositiveNumber2 -4 5) should return 2. 2. Method name: lowestAlphabetically Parameter(s): A String of lower-case words separated by spaces and made up of the letters a-z. The String will have at least one word.

Return value: A String containing the lowest alphabetical word. The String method comparelo0 does a lexicographic comparison between two strings, which allows you to test for the lowest alphabetical word. Read documentation on compareTo in order to understand how to use it. Example: lowestAlphabetically cat dog apple fish) would return apple 3. Method name: findSmallestNumberlnTwoStrings Parameter(s): Two String parameters. Each string is made up of numbers separated by spaces. The first string must have at least one number. Return value: An int containing the smallest number found in the two strings. Example: findSmallestNumberlnTwoStrings(12 3 5 2-1 10) would return -1 4. Method name: curveScores Parameter(s): A String containing numbers from O to 100. Each number is separated by a space. There must be at least one number in the String. Return value: A String of numbers scaled so that the highest number in the parameter String becomes 100 and all the other numbers are moved up by the same amount. This String should also be numbers separated by spaces with no additional characters. Example: curveScores(45 85 90) would return 55 95 100 5. Method name: containsThisColor Parameter(s): A Picture object that is at least 1x1 pixels and a Color object Return value: A boolean value. Return true if the Color parameter matches one of the pixels in the image and false otherwise. A color match is done by using the equals method rather than-- Example: For a 1 pixel picture with a color of (100, 200, 50) and a color to search for of (100, 100, 100), this method would return false,

1 package a3; Compilation: javac Picture.javal 20 21㊥ import Java.awt.Color:D 41 42/** 43 This class provides methods for manipulating individual pixels of 44an image using the RGB color format. The alpha component (for transparency) 45 * is not currently supported. 46The original image can be read from a f@code PNG), (@code GIF), 47or {@code 3PEG) file or the user can create a blank image of a given dimension. 48 This class includes methods for displaying the image in a window on 49the screen or saving it to a file 50 * <p> 51 *Pixel (<em> col</em>, <em>row</em>) is column <em>col/e> and row <em>row</em>. 52* By default, the origin (e, 0) is the pixel in the top-left corner, 53 which is a common convention in image processing. 54 * The method {@link #setoriginLowerLeft()) change the origin to the lower left 55 *<p> 56 The (@code get()) and (@code setO methods use {@link Color objects to get 57*or set the color of the specified pixel 58 The @code getRGB) and (@code setRGB) methods use a 32-bit (@code int) 59 *to encode the color, thereby avoiding the need to create temporary 60 *@code Color objects. The red (R), green (G), and blue (B) components 61 are encoded using the least significant 24 bits. 62 Given a 32-bit (@code int encoding the color, the following code extracts 63 the RGB components: 64 * <blockquotexprex 65 * int r = (rgb >> 16) & 0xFF; 66 * int g= (rgb>> 8) & 0xFF; 67 * int b= (rgb>> 0) & 0xFF; 68 /prex/blockquote> 69 Given the RGB components (8-bits each) of a color, 70 *the following statement packs it into a 32-bit (@code intj: 71 * <blockquote><pre> 72 * int rgb (r << 16) + (g << 8) + (b << 0); 73/prex/blockquote> 74 *<p> 75 A <em>WK/em>-by-Ken>H</em> picture uses 4 Kem>W Hk/em> bytes of memory, 76 *since the color of each pixel is encoded as a 32-bit <code int</code>. 77*<p>

78 For additional documentation, see 79 *a href-https://introcs.cs.princeton.edu/31datatype Section 3.1</a> of 80 * <1>Computer Science: An Interdisciplinary Approach</i> 81by Robert Sedgewick and Kevin Wayne 82 *See (@link GrayscalePicture for a version that supports grayscale images. 84 *@author Robert Sedgewick 85author Kevin Wayne 86*/ 87 public final class Picture implements ActionListener { private BufferedImage image; private JFrame frame; private String filename; private boolean isOriginUppe r Left = true; // location of origin private final int width, height; // the rasterized image // on-screen view // name of file 89 90 91 92 93 94 ** 95 96 97 98 // width and height Creates a f@code width-by-(@code height picture, with @code width columns * and @code height} rows, where each pixel is black. @param width the width of the picture @param height the height of the picture @throws IllegalArgumentException if @code width is negative @throws IllegalArgumentException if @code height) is negative 100 101 102 103 public Picture(int width, int height) 104 105 106 107 108 109 110 if (width <0) throw new IllegalArgumentException(width must be non-negative); if (height く 0) throw new IllegalArgumentException (height must be non-negative); this.width -width this. height = height; image new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) // set to TYPE_INT_ARGB here and in next constructor to support transparency *Creates a new picture that is a deep copy of the argument picture. 114 115 116 Oparam picture the picture to copy @throws IllegalArgumentException if @code picture) is (@code null) public Picture(Picture picture) { 118 119 120 if (picturenull) throw new IllegalArgumentException(constructor argument is null);

164 165 166 167 168 169 catch (IOException ioe) { throw new IllegalArgumentException(could not open image file: filename, ioe); *Creates a picture by reading the image from a PNG, GIF, or JPEG file. 172 173 174 175 176 177 public Picture(File file) { 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192) 193 1949/** 195 196 197 198 199 200e public JLabel getJLabel() f 201 202 203 204 205 206e /** @param file the file @throws IllegalArgumentException if cannot read image @throws IllegalArgumentException if (@code filej is (@code null) if (filenull) throw new IllegalArgumentException(constructor argument is nul1); tr image -ImageIO.read(file); catch (IOException ioe) { throw new IllegalArgumentException(could not open file: + file, ioe); if (imagenul1) { throw new IllegalArgumentException(could not read file: + file); width -image.getwidth(null); heightimage.getHeight (null); filename-file.getNameO; Returns a (@link JLabel containing this picture, for embedding in a (@link 3Panel), * {@link JFrame or other GUI widget. *@return the (@code JLabel) if (imagenul1) return null; ImageIcon icon - new ImageIcon(image); return new JLabel(icon) // no image available

207 208 209e public void setOriginUpperLeft() 210 211 212 *Sets the origin to be the upper left pixel. This is the default. isOriginUpperLeft-true; 214 215 216 public void setOriginLowerLeft() { 217 218) 219 *Sets the origin to be the lower left pixel. isOriginUpperLeft -false; 221 Displays the picture in a window on the screen 223e public void show() 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 // create the GUI for viewing the image if needed if (framenull) frame = new JFrame(); JMenuBar menuBar -new JMenuBar(); JMenu menunew JMenu(File); menuBar.add(menu); JMenuItem menuItem1 -new JMenuItem( Save...); menuItem1.addActionListener(this); // use getMenuShortcutKeyMaskEx() in Java 10 (getMenuShortcutKeyMask() deprecated) menuItem1.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add (menuItem1); frame.setJMenuBar(menuBar); frame.setContentPane(getJLabel()); // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON CLOSE); if (filenamenull) frame.setTitle(width-by-+ height); else frame.setResizable(false); frame.pack(); frame.setVisible(true); frame.setTitle(filename);

250 251 252 253 254 255 256 /** 257 258 259 260 // draw frame.repaint() Returns the height of the picture. Oreturn the height of the picture (in pixels) public int height) 262 263 264 265 /** 266 267 268 269 270 271 272 273 274 private void validateRowIndex(int row) 275 276 277) 278 279 private void validateColumnIndex(int col) { 280 281 282) 283 284 /** 285 286 287 288 289 290 291 292 public Color get(int col, int row) f return height; *Returns the width of the picture. *Oreturn the width of the picture (in pixels) public int width) return width if (row < 0 | | row >= height()) throw new IllegalArgumentException(row index must be between 0 and + (height() - 1) + : + row); if (col < 0 11 col >= width()) throw new IllegalArgumentException(column index must be between0 and + (width() - 1) + : + col); Returns the color of pixel (@code col), @code row)) as a (@link java.awt.Color). @param col the column index @param row the row index ereturn the color of pixel (f@code col), (@code row)) * @throws IllegalArgumentException unless both {@code 0 <= col < width) and {@code 0 (z row < height) x/

293 294 295 296 297 298 299 /** 300 301 302 303 304 305 306 307 308 309 public int getRGB(int col, int row) { 310 311 312 313 314 315 316 17** 318 319 320 321 322 323 324 325 326 public void set(int col, int row, Color color) f 327 328 329 330 331 332 ) validateColumnIndex(col); validateRowIndex(row); int rgb getRGB (col, row); return new Color (rgb); Returns the color of pixel (@code colj, @code row]) as an @code int) * Using this method can be more efficient than {@link #get(int, ịnt)} because *it does not create a @code Color) object. @param col the column index Oparam row the row index * ereturn the integer representation of the color of pixel (@code col), (@code row)) * @throws IllegalArgumentException unless both {@code 0仁col < width) and {@code 0仁row 〈 height) validateColumnIndex(col); validateRowIndex(row); if (isOriginUpperLeft) return image.getRGB (col, row); else return image.getRGB (col, height - row - 1); * Sets the color of pixel (@code col), (@code row)) to given color. eparam col the column index @param row the row index *@param color the color * @throws IllegalArgumentException unless both {@code 0 <= col < width) and {@code 0 <= row < height) ethrows IllegalArgumentException if @code color is @code null) validateColumnIndex(col); validateRowIndex (row); if (colornull) throw new IllegalArgumentException(color argument is null); int rgb color . getRGB(); setRGB (col, row, rgb); 334 /** 335 * Sets the color of pixel (@code col), (@code row)) to given color.

336 337 338 339 340 @param col the column index @param row the row index @param rgb the integer representation of the color * @throws IllegalArgumentException unless both {@code 0 <= col < width) and {@code 0 <= row < height) 342 public void setRGB(int col, int row, int rgb) { 343 344 345 346 347) 348 /** 349 350 validateColumnIndex(col); validateRowIndex (row); if (isOriginUpperLeft) image.setRGB (col, row, rgb); else image.setRGB (col, height - row - 1, rgb); Returns true if this picture is equal to the argument picture. Oparam other the other picture @return @code true if this picture is the same dimension as @code other 352 and if all pixels have the same color; @code false) otherwise 354 -355epublic boolean equals (Object other) { 356 357 358 359 360 if (otherthis) return true if (othernull) return false; if (other.getClass() this.getClass() return false; Picture that-(Picture) other; if (this.width) that.width()) return false; if (this.height)!- that.height()) return false for (int col 0; col< width); col++) 362 363 364 365 366) 367 for (int row = 0; row < height(); row++) if (this.getRGB(col, row) that.getRGB (col, row)) return false; return true; 368* 369 370 371 372 373 374 375 376epublic String toString() { Returns a string representation of this picture. The result is a <code>width</code-by-<code>height</code matrix of pixels, the red, green, and blue components. @return a string representation of this picture *where the color of a pixel is represented using 6 hex digits to encode StringBuilder sb = new StringBuilder(); sb.append(width +-by-height picture (RGB values given in hex) ); 378

379 380 381 382 383 384 385 386 387 388 389 390 391 /** 392 393 394 395 396 for (int row = 0; row < height; row++) { for (int col 0; col< width; col++) { int rgb 0; if (isOriginUpperLeft) rgb = image . getRGB(col, row); else sb.append(string.format(.4%06x , rgb & 0xFFFFFF)); rgbimage.getRGB(col, height - row - 1); sb.append( ); return sb.toString).trim); This operation is not supported because pictures are mutable. Oreturn does not return a value * @throws UnsupportedOperationException if called *I -397epublic int hashCode() f 398 399 400 401 /** 402 403 404 405 406 407 408 public void save(String name) 1 409 410 411 412 ) 413 14 /** 415 416 417 418 419 420 public void save(File file) { 421 throw new UnsupportedOperationException(hashCode) is not supported because pictures are mutable); Saves the picture to a file in either PNG or JPEG format. * The filetype extension must be either -png or -jpg. @param name the name of the file * @throws IllegalArgumentException if {@code name) is (@code null) if (namenull) throw new IllegalArgumentException (argument to save() is null); save (new File(name)); filename name Saves the picture to a file in a PNG or JPEG image format. @param file the file * @throws IllegalArgumentException if {@code file) İs {@code null} if (filenull) throw new IllegalArgumentException(argument to save() is null);

420 public void save(File file) { 421 422 423 424 425 426 427 428 429 430 if (filenull) throw new IllegalArgumentException(argument to save() is null); filename-file.getNameO; if (framenul1) frame.setTitle(filename); string suffix filename . substring(filename . ÎastIndex0t(.) + 1); if (jpg.equalsIgnoreCase(suffix) 1l png.equalsIgnoreCase(suffix)) ( tr ImageIO.write(image, suffix, file); catch (IOException e) { e.printStackTrace(); 432 433 434 else System.out.println(Error: filename must end in -jpg or -png); 437 438 /** Opens a save dialog box when the user selects Save As from the menu. 440 441 @Override △442 public void actionPerformed(ActionEvent e) { 443 FileDialog chooser new FileDialog(frame, Use a png or .jpg extension, FileDialog.SAVE) chooser.setVisible(true); if (chooser.getFile() != null) 445 446 447 448 449 450 451 /** 452 { save (chooser.getDirectory) File.separator chooser.getFile()); * Unit tests this (@code Picture data type. Reads a picture specified by the command-line argument, * and shows it in a window on the screen. 454 455 456 457 458 459 460 461 462 Oparam args the command-line arguments public static void main(String[] args) {

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution