Java Program to Convert Hex Color Code to RGB Value
This Java program converts a hex color code (e.g., '#ffffff') to its corresponding RGB value (e.g., RGB(255,255,255)). The program takes the hex input as a command-line argument and prints the RGB output.
public class HexToRGBConverter {
public static void main(String[] args) {
// Check if the hex color code is provided as a command line argument
if (args.length == 0) {
System.out.println("Hex color code not provided.");
return;
}
// Get the hex color code from the command line argument
String hexCode = args[0];
// Remove the '#' symbol if present
if (hexCode.startsWith("#")) {
hexCode = hexCode.substring(1);
}
// Check if the hex color code is valid
if (hexCode.length() != 6) {
System.out.println("Invalid hex color code.");
return;
}
// Extract the red, green, and blue components from the hex color code
int red = Integer.parseInt(hexCode.substring(0, 2), 16);
int green = Integer.parseInt(hexCode.substring(2, 4), 16);
int blue = Integer.parseInt(hexCode.substring(4, 6), 16);
// Print the RGB value
System.out.println("RGB(" + red + "," + green + "," + blue + ")");
}
}
To run this program, open a command prompt or terminal, navigate to the directory where the Java file is saved, and compile and run the program using the following commands:
javac HexToRGBConverter.java
java HexToRGBConverter #ffffff
Replace '#ffffff' with any hex color code you want to convert to RGB. The program will output the corresponding RGB value.
原文地址: https://www.cveoy.top/t/topic/RQz 著作权归作者所有。请勿转载和采集!