|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class ColorCodeConverter { |
| 4 | + public static void main(String[] args) { |
| 5 | + Scanner scanner = new Scanner(System.in); |
| 6 | + System.out.println("Color Code Converter"); |
| 7 | + System.out.println("1. RGB to HEX"); |
| 8 | + System.out.println("2. HEX to RGB"); |
| 9 | + System.out.print("Enter your choice (1 or 2): "); |
| 10 | + |
| 11 | + int choice = scanner.nextInt(); |
| 12 | + scanner.nextLine(); // Consume the newline character |
| 13 | + |
| 14 | + if (choice == 1) { |
| 15 | + System.out.print("Enter RGB color (e.g., 255, 0, 0): "); |
| 16 | + String rgb = scanner.nextLine(); |
| 17 | + String hex = rgbToHex(rgb); |
| 18 | + System.out.println("HEX color: " + hex); |
| 19 | + } else if (choice == 2) { |
| 20 | + System.out.print("Enter HEX color (e.g., #FF0000): "); |
| 21 | + String hex = scanner.nextLine(); |
| 22 | + String rgb = hexToRgb(hex); |
| 23 | + System.out.println("RGB color: " + rgb); |
| 24 | + } else { |
| 25 | + System.out.println("Invalid choice. Please select 1 or 2."); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public static String rgbToHex(String rgb) { |
| 30 | + String[] values = rgb.split(","); |
| 31 | + if (values.length != 3) { |
| 32 | + return "Invalid RGB format"; |
| 33 | + } |
| 34 | + int r = Integer.parseInt(values[0]); |
| 35 | + int g = Integer.parseInt(values[1]); |
| 36 | + int b = Integer.parseInt(values[2]); |
| 37 | + |
| 38 | + return String.format("#%02X%02X%02X", r, g, b); |
| 39 | + } |
| 40 | + |
| 41 | + public static String hexToRgb(String hex) { |
| 42 | + if (hex.startsWith("#")) { |
| 43 | + hex = hex.substring(1); |
| 44 | + } |
| 45 | + |
| 46 | + int intValue = Integer.parseInt(hex, 16); |
| 47 | + int r = (intValue >> 16) & 0xFF; |
| 48 | + int g = (intValue >> 8) & 0xFF; |
| 49 | + int b = intValue & 0xFF; |
| 50 | + |
| 51 | + return r + ", " + g + ", " + b; |
| 52 | + } |
| 53 | +} |
0 commit comments