[英]Parse digits from integer
我需要制作一个将颜色填充到Rectangle
的函数。 方法看起来像这样
public void fillRect(Rectangle rect, int color)
{
int red = color;
int green = color;
int blue = color;
g.setColor(new Color(red, green, blue));
g.fillRect(rect.getX(), rect.getY(), rect.getW(), rect.getH());
}
我想使用整数作为参数,例如200100150
,它将导致红色的值200
(仅前三个数字)。
可以做这个宽度的Java吗?
您可以使用'%'和'/'这样的操作来实现:
int blue = color % 1000;
color /= 1000;
int green = color % 1000;
color /= 1000;
int red = color;
您也可以在开始时添加一个简单的验证
if(color <= 99_999_999) { // I'm pretty sure that you need at least JDK7 to use '_' notation
//do sth
}
如果您知道数字长度(即看起来所有整数的长度都为9),则可以使用模数和(整数)除法:
int red = color / 1000000;
int green = color % 1000000 / 1000;
int blue = color % 1000;
如果不是,则可以将整数转换为字符串,将前三个字符作为子字符串,然后将其转换回整数。
转换为字符串并获取子字符串,然后再次将其转换为整数? 好主意。这是我的代码
public void setColor(int color)
{
String newColor = Integer.toString(color);
g.setColor(new Color(Integer.parseInt(newColor.substring(0, 3)),
Integer.parseInt(newColor.substring(3, 6)),
Integer.parseInt(newColor.substring(6, 9))));
}
这比将整数传递给Color()慢得多? 我是Java新手,我想按自己的方式做事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.