-2

我必须在我的 java 程序中将 RGB 颜色代码转换为十六进制代码,但我不知道该怎么做。我应该使用 System.out.printf() 语句进行转换。

任何人都可以向我展示如何在 Java 中执行此操作的示例吗?我真的很感激!

4

2 回答 2

5

我认为您只是在问如何获取三个十进制整数,例如rgb(0, 100, 255)并将其转换为单个十六进制字符串,就像他们在 HTML 中使用的那样,例如#0064FF. 我会使用printf而不是println

System.out.printf("#%02X%02X%02X%n", red, green, blue);

如果您真的打算使用println,那么您可以String.format用于转换:

System.out.println(String.format("#%02X%02X%02X", red, green, blue));

如果您想了解它是如何工作的,可以阅读Java 的 Format String Syntax。基本上,%02X意味着:打印int一个两位大写十六进制数,必要时用零填充。他们还建议在字符串末尾使用%n而不是换行符,因为它更独立于平台(它在 Windows 上被翻译)。\n\r\n

于 2013-10-17T15:11:00.240 回答
0

There are a few different ways to do this. Here are a few ideas.

If you ALWAYS want the object to show the hex value when printed override your toString() so that it gives you the correct output. This is not optimal... What if you decide in the future your toString() needs to do something different?

A better way would be to add a public String asHex() method that way its always clear what your doing. Then you can:

System.out.println(new rgb(0, 0, 0).asHex());

And you would see a #000000

于 2013-10-17T15:29:21.013 回答