I had to write a program to convert RGB to CMYK. When I tried running the program I received a java.lang.NullPointerException error. After using a debugger it showed me it had to do with when I called the PrintRGB(RGB) method in the main. I am new to coding and am unsure how to fix this. I googled it and across a few answers but didn't make sense to me since this is my first time coding. Please help me understand this error so I can fix my code. Thank you.
//Reads the data from the file , populates RGB and converts the colors to CMYK.
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("colors.txt"));
PrintStream ps = new PrintStream("ArrayResults.txt");
int[] RGB = new int[3];
double[] CMYK = new double[4];
while (sc.hasNextInt()) {
RGB[0] = sc.nextInt();
RGB[1] = sc.nextInt();
RGB[2] = sc.nextInt();
if (validateRGB(RGB)) {
RGBtoCMYK(RGB,CMYK);
printRGB(RGB);
printCMYK(CMYK);
}
else{
ps.println("invalid numbers");
}
}
}
//Receives the array RGB and determines whether the values are valid.
public static boolean validateRGB(int[] RGB) throws Exception {
Scanner sc = new Scanner(new File("colors.txt"));
for (int i = 0; i < 3; i++) {
if (RGB[i] >= 0 && RGB[i] <= 255) {
return true;
}
}
return false;
}
//Returns the maximum value in array x which is used to determine white.
public static int maximum(int x[]) {
int maximum, i;
maximum = x[0];
for (i = 1; i < 3; i++) {
if (x[i] > maximum) {
maximum = x[i];
}
}
return maximum;
}
//Receives array RGB and places the converted values into array CMYK.
public static void RGBtoCMYK(int RGB[], double CMYK[]) throws Exception {
double w;
w = Math.abs(maximum(RGB) / 255.0);
CMYK[0] = (w - (RGB[0] / 255.0)) / w;
CMYK[1] = (w - (RGB[1] / 255.0)) / w;
CMYK[2] = (w - (RGB[2] / 255.0)) / w;
CMYK[3] = 1.0 - w;
}
//Receives array RGB and prints the values in the array.
public static void printRGB(int RGB[]) throws Exception {
for (int i = 0; i < 3; i++) {
ps.println(RGB[i]);
}
}
//Receives array CMYK and prints the values in the array.
public static void printCMYK(double CMYK[]) throws Exception {
for (int i = 0; i < 4; i++) {
ps.println(CMYK[i]);
}
}
}