Can someone take a look at this code for me and tell me what I need to change to
ID: 3803743 • Letter: C
Question
Can someone take a look at this code for me and tell me what I need to change to get my negateRed method working properly. It is supposed to change every third element in the array( starting at 0, 3, 6, 9, etc ) but instead it changes every single value in my array. Please let me know what you find. Thanks.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
public class PPM {
public static void main ( String args[] ) {
try {
System.out.print ( " PPM Image Processor " );
Scanner keyboard = new Scanner ( System.in );
System.out.print ( " Enter input filename: " );
String inFile;
inFile = keyboard.next();
File file = new File( inFile );
Scanner input = new Scanner ( file );
String first = input.next();
int columns = input.nextInt();
int row = input.nextInt();
int max = input.nextInt();
int x = ( columns * 3 );
int y = 0;
int buffer[] = new int [x];
Scanner keyboardTwo = new Scanner ( System.in );
String outFile;
System.out.print ( "Enter output filename: " );
outFile = keyboardTwo.next();
PrintWriter writer = new PrintWriter ( outFile );
writer.println ( first );
writer.print ( columns );
writer.printf ( " %d", row );
writer.printf ( " %d ", max );
while ( input.hasNext() ) {
if ( y < x ) {
int v = input.nextInt();
buffer[y] = v; negateRed ( buffer, columns );
writer.println ( buffer[y++] );
}
else {
int k = 0;
int v = input.nextInt();
buffer[k] = v; negateRed ( buffer, columns );
while ( k < x ) {
writer.println ( buffer[k++] );
}
}
y = 0;
}
writer.close();
}
catch ( Exception ex ) {
System.out.println ( "An error has occurred!" );
ex.printStackTrace();
}
}
/**
* negateRed
*
* This method negates the red value in the image. All P3-format
* PPM images have an image depth of 255, which are used in
* the method's calculations.
*
* @param buffer an integer array containing the image buffer
* @param columns an integer w/ the number of columns in the image
* @return NONE
*/
public static void negateRed ( int [] buffer, int columns ) {
int x = columns * 3;
for ( int i = 0; i < x; i++ ) {
if ( i % 3 == 0 ) {
buffer[i] = 255 - buffer[i];
}
}
}
}
Explanation / Answer
solution:
when calling the function negateRed ( buffer, columns );
pass the parameter 'X' in place of 'columns' to make the code work
replace the line
negateRed ( buffer, columns );
with
negateRed ( buffer, X);