简体   繁体   English

解析整数中的数字

[英]Parse digits from integer

I need to make a function that will fill a Rectangle with a color. 我需要制作一个将颜色填充到Rectangle的函数。 The method looks like this 方法看起来像这样

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());
}

I would like to use an integer as parameter, for example 200100150 which would result in the value 200 for red (only the three first digits). 我想使用整数作为参数,例如200100150 ,它将导致红色的值200 (仅前三个数字)。

Is it possible to do this width java? 可以做这个宽度的Java吗?

You can do it with '%' and '/' operations like this: 您可以使用'%'和'/'这样的操作来实现:

int blue = color % 1000;
color /= 1000;

int green = color % 1000;
color /= 1000;

int red = color;

Also you could add a simple validation at the beginning 您也可以在开始时添加一个简单的验证

if(color <= 99_999_999) { // I'm pretty sure that you need at least JDK7 to use '_' notation
    //do sth
}

If you know the number length (ie, it looks like all your integers will be of length 9), you can use modulus and (integer) division: 如果您知道数字长度(即看起来所有整数的长度都为9),则可以使用模数和(整数)除法:

int red = color / 1000000;
int green = color % 1000000 / 1000;
int blue = color % 1000;

If not, you can turn the integer into a String, get the first three characters as a substring, and convert it back to an integer. 如果不是,则可以将整数转换为字符串,将前三个字符作为子字符串,然后将其转换回整数。

Converting to a string and get Substrings and convert them to integers again? 转换为字符串并获取子字符串,然后再次将其转换为整数? Great idea.Here is my code 好主意。这是我的代码

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))));
}

It will be much slower than passing the integer to the Color()? 这比将整数传递给Color()慢得多? Im new in java and i want to make things my way. 我是Java新手,我想按自己的方式做事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM