java之 ------ 类的封装、继承和多态(四)

时间:2020-11-24 21:56:10

问题:

声明颜色类Color。一种颜色由(红、绿、蓝)三元色值组成,称为RGB值。一个int整数可表示一种颜色,结构为:最高字节全1,其后3字节分别存储“红、绿、蓝”单色值,单色值范围是0255。例如,0xff00ff00表示绿色,RGB值为(0,255,0)

声明Color颜色类

RGB颜色值说明见教材实验3RGB整数结构如图3.4所示,常用颜色及其RGB值如表3-1所示。

图1.1 颜色RGB整数结构图

表1-1 颜色及其RGB

颜色

RGB

RGB值的十六进制

java.awt.Color常量

(255,0,0)

0xffff0000

Color.red

绿

(0,255,0)

0xff00ff00

Color.green

(0,0,255)

0xff0000ff

Color.blue

(0,0,0)

0xff000000

Color.black

(255,255,255)

0xffffffff

Color.white

Color颜色类主要成员声明如下,再声明表示红、绿、蓝、黑、白等颜色的常量。

public class Color {                           //颜色类
private int value; //颜色值

public Color(int red, int green, int blue) //以三元色构造颜色对象
public Color(int rgb) //以三元色构造颜色对象
public int getRGB() //返回颜色对象的RGB值
public int getRed() //返回颜色对象的红色值
public int getGreen() //返回颜色对象的绿色值
public int getBlue() //返回颜色对象的蓝色值
public String toString() //返回颜色对象的字符串描述
}

代码实现:

import java.util.*;
public class Color{
private int value;
int red,green,blue;
public Color(int red,int green,int blue){
this.set(red,green,blue);
this.value=blue+(green<<8)+(red<<16)+(255<<24);
}
public Color(int rgb){
this.value=rgb;
this.set(rgb);
}
public void set(int rgb){
this.blue=this.value&255;
this.green=(this.value&(255<<8))>>8;
this.red=(this.value&(255<<16))>>16;
}
public void set(int red,int green,int blue){
this.red=red;
this.green=green;
this.blue=blue;
}
public String getRGB(){
return Integer.toHexString(this.value);
}
public int getRed(){
return this.red;
}
public int getGreen(){
return this.green;
}
public int getBlue(){
return this.blue;
}
public String toString(){
return "( red , green , blue ) === ( "+this.red+" , "+this.green+" , "+this.blue+" )";
}
}
class Main{
public static void main(String[] args){
final int MIN=-16777216;
Scanner sc=new Scanner(System.in);
int a=(255<<24)+(255<<16)+(255<<8)+255;
//System.out.println("Please input n ( "+a+"<=a<="+(255<<24)+")");
System.out.println("Please input red ,green and blue`s single color value");
System.out.println("( 0<=value <=255 ) :");
while(sc.hasNext()){
Color c=new Color(sc.nextInt(),sc.nextInt(),sc.nextInt());
System.out.println(c);
System.out.println("RGB = 0x"+c.getRGB());
System.out.println("Red = "+c.getRed());
System.out.println("Green = "+c.getGreen());
System.out.println("Blue = "+c.getBlue());
System.out.println("-----------------");
System.out.println("Please input n ( "+MIN+" <= n <= -1) : ");
c=new Color(sc.nextInt());
System.out.println(c);
System.out.println("RGB = 0x"+c.getRGB());
System.out.println("Red = "+c.getRed());
System.out.println("Green "+c.getGreen());
System.out.println("Blue = "+c.getBlue());
System.out.println();
System.out.println("Please input red ,green and blue`s single color value :");
}

}
}