String [] rnum = {"Black", "Red", "Black", "Red", "Black", "Red", "Black","Red",
"Black", "Red", "Black", "Red", "Black", "Red", "Black", "Red","Black", "Red", "Green"};
int A = rnum.length;
//the "Math.random() method will get you a random color
int random = (int) (Math.random() * A);
//randomize the strings
String Color = rnum[random];
How do i say "if color = black then do this" or same for green or same for red"
You mean...
if(Color.equals("Black")) {
// then do this
} else if(Color.equals("Red"){
// then do this
}
or even (In Java >= 1.7)
switch(Color) {
case "Black":
// then do this
break;
case "Red":
// then do this
break;
}
Color should not be capitalized, since that can be a Java class name.
For this purpose you can use a ternary operator (shortened if-else):
String color = ( rnum[random].compareTo("Black") == 0 ? ** do something here ** : ** do something if the color is not "Black" ** );
or:
String color = "";
if(rnum[random].compareTo("Black") == 0) {
// do stuff
}
else {
// it's not black. do other stuff.
}
With red and green, just replace "Black" with "Red", or "Green".
Using java equals method for each color is the simplest way.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29
Others said the method to decide equality, I would add up something about the algorithm.
Consider adding weight of colours, I see Red and Black appear 9 times while Green appears once. I would add an object containing the name of the colour and the weight you want to apply. Like {"Green", 1}, {"Red", 9}, {"Black", 9}.
Sum up the weights and order the colours in some way and decide where the random number fell.
It would make more clean code and nicer solution.
Related
i'm having trouble trying to sort an ArrayListof Color.
I'm retrieving all the colors from this image
imgRed.jpg
The code i'm using:
public static ArrayList<Color> getColors(BufferedImage img){
int height = img.getHeight();
int width = img.getWidth();
boolean found = false;
ArrayList<Color> List = new ArrayList<>();
for(int x=0;x<width;x++) {
for(int y=0;y<height;y++) {
found = false;
Color color = new Color(img.getRGB(x, y));
for(Color c : List) {
if(color.getRGB()<c.getRGB()+100 && color.getRGB()>c.getRGB()-100) {
found=true;
}
}
if(!found) {
List.add(color);
}
}
}
return List;
}
After i've collected all the colors, i sort them:
Collections.sort(Colors, Comparator.comparing(Color::getRed)
.thenComparing(Color::getGreen)
.thenComparing(Color::getBlue));
Subsequently i create a new image containing all the colors sorted:
public static void createImage(ArrayList<Color> Colors) {
int width=500;
int height=Colors.size()*10;
BufferedImage b_img = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = b_img.createGraphics();
int partialHeight = 0;
int amount = Colors.size();
for(Color c : Colors) {
System.out.println("Colors remaining: "+amount);
graphics.setPaint ( c );
graphics.fillRect ( 0, partialHeight, b_img.getWidth(), partialHeight+10 );
partialHeight = partialHeight + 10;
amount--;
}
File outFile = new File("C:/test/img/out/testColor/outputRed4.png");
try {
ImageIO.write(b_img, "png", outFile);
} catch (IOException e) {
e.printStackTrace();
}
}
This function produces this image: outputRed.png
As you can see, the colors are not really sorted. This is because (i think) colors are sorted basing its numeric value (Red, Green, Blue) and because the RGB numeric value isn't ordered by our perspective.
I remember that the image produced hasn't a color twice so all the color in that image are different.
My question is:
How can i order all the colors following all the shades of each color without having such a jagged result?
Thanks to all
The issue you are encountering comes from the fact that you are taking 3-dimensional data (red values, green values, blue values) and trying to order them in 1 dimension (a List with only an index parameter).
The output you are receiving is most likely exactly what you should expect if you sort first, by the red value of a colour, and then by the green, and then blue. Remember, this method only compares the green value to sort colours with identical red values, and similarly only compares the blue value to sort colours with identical red and blue values.
Perhaps the reason it looks "jagged" is because of the suddenly changing intensity. Given that the input image is pretty much entirely shades of red at different intensities, it might be worth using Comparator.comparing(Color::getTotal) where getTotal() is defined as:
int getTotal() {
return getGreen() + getBlue() + getRed();
}
This will sort by intensity (i.e. brightness), and will make the image look less "jagged", but on images with more than just red, the colours will not be in "colour order" or "rainbow order".
Again, this is an issue of trying to map 3-d data into a 1-d space. Compromises will always have to be made.
How can I print a color in RGB format? I am using Robot(java.awt) to get the color of a random pixel on the screen and I want to print it as RGB. So if the pixel is completely red, the output should be
rgb(255, 0, 0)
Is there something I can do? Should I get the individual red green and blue values(and how can I do that)? Here's what I got so far:
public static void main(String[] args) {
Random rand = new Random();
Robot r = null;
int screenHeight = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
int screenWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
try {
r = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
Color pixelColor = r.getPixelColor(rand.nextInt(screenHeight), rand.nextInt(screenWidth));
System.out.println(pixelColor);
System.exit(0);
}
But it outputs this(random example):
java.awt.Color[r=222,g=228,b=239]
EDIT: I also tried using getRGB() but it still does not work.
//...
Color pixelColor = r.getPixelColor(rand.nextInt(screenHeight), rand.nextInt(screenWidth));
System.out.println(pixelColor.getRGB());
//...
But it outputs(random example):
-723724
What do these numbers mean?
Let's start by having a look at a really simple test
Color color = Color.RED;
System.out.println(color);
System.out.println(color.getRGB());
System.out.println(color.getRed() + ", " + color.getGreen() + ", " + color.getBlue());
Which outputs
java.awt.Color[r=255,g=0,b=0]
-65536
255, 0, 0
The first is the Color objects toString method, which is providing you information about the class and the properties, as you can see, the red property is 255
The second is a integer packed value (the red, green and blue (and alpha) properties all packed into a single int value)
The last is, obviously, each individual property of the color, which would seem to be what you're actually after.
What I think you should do, is go have a read of the JavaDocs on the Color class so you better understand what information it provides, rather then randomly taking stabs at what you think it should provide
I am writing a program where I take an image determine the average red channel, green channel and blue channel present in that image. I take these averages and pass them as parameters to a new color. I then want to add this color to an array. I repeat this process 24 times. The problem I face is that when I get a new color and add it to the array the previous colors get erased. I want to preserve the existing colors in the array and add to the one that hasn't been filled yet. Here is what I have tried.
System.out.println("R: "+ rAvg);
System.out.println("G: "+ gAvg);
System.out.println("B: "+ bAvg);
Color newColor = new Color(rAvg, gAvg, bAvg);
Color[] ColorArr = new Color[24];
for(int i = 0; i < ColorArr.length; i++){
ColorArr[i] = newColor;
}
System.out.println(Arrays.toString(ColorArr));
Here is the output after one color is added to the array
R: 206
G: 0
B: 0
[java.awt.Color[r=206,g=0,b=0],java.awt.Color[r=206,g=0,b=0]
Here is the array after I add a new color.
R: 211
G: 178
B: 230
[java.awt.Color[r=211,g=178,b=230], java.awt.Color[r=211,g=178,b=230]
The last color gets overwritten and replaced with the new color instead of going in the next index and preserving the last. How can I fix this so I preserve the entered colors in the array and place the new color the index after the previous?
You can restructure your code to something like this:
private Color[] colorArray = new Color[24];
private int currentIndex = 0;
public void addColorToArray(int red, int green, int blue) {
colorArray[currentIndex++] = new Color(red, green, blue);
}
public void myMethodThatDoThis24Times() {
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
...
}
Your logic looks correct. The only thing which you need to take care is creating a new instance of color object every time.
//ColorArr[i] = newColor; // Instead of this
ColorArr[i] = new Color(rAvg, gAvg, bAvg); // Do this for each element in array
You were initially doing Color newColor = new Color(rAvg, gAvg, bAvg); and assign the same newColor instance to all the elements in the ColorArr.
Thus, a single change in the newColor instance was reflecting the change in all its referenced elements in the array.
As #user alayor, rightly suggested to create new instances of Color(rAvg, gAvg, bAvg) with different RGB values.
I want to generate randomly one of three colours, either red,blue,white. I want to create a program that randomly generated one these colours to a person when after they enter their name in java. The purpose of the program would be for the user to enter a name and the out put would be that" name is assigned to either red, blue, or white"
Create an array:
String[] colors = {"red", "blue", "white"};
Generate a random number between 0 and 2:
Random rand = new Random();
int random = rand.nextInt((2 - 0) + 1);
Get the random color:
String randomColor = colors[random];
I have used "combinatoricslib" to Generate combination from a object array. But the result is displayed as a vector. I want to know how to read only one value.
Here is the code.
// Create the initial vector
ICombinatoricsVector<String> initialVector = Factory.createVector(
new String[] { "red", "black", "white", "green", "blue" } );
// Create a simple combination generator to generate 3-combinations of the initial vector
Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 3);
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(combination);
}
This is the result.
CombinatoricsVector=([red, black, white], size=3)
CombinatoricsVector=([red, black, green], size=3)
CombinatoricsVector=([red, black, blue], size=3)
CombinatoricsVector=([red, white, green], size=3)
CombinatoricsVector=([red, white, blue], size=3)
CombinatoricsVector=([red, green, blue], size=3)
CombinatoricsVector=([black, white, green], size=3)
CombinatoricsVector=([black, white, blue], size=3)
CombinatoricsVector=([black, green, blue], size=3)
CombinatoricsVector=([white, green, blue], size=3)
But it has both combination array and size. But i want to get only the array. how to get it.
Please help me. I am new to java.
Thanks in advance.
You simply need to read the javadoc. It took me 5 seconds to google it and find it: http://combinatoricslib.googlecode.com/svn/tags/release21/doc/org/paukov/combinatorics/ICombinatoricsVector.html
java.util.List<T> getVector()
Returns vector as a list of elements
I understand that what you're using here is an instance of combinatorics.CombinatoricsVector
It has a getVector method, which returns a List of all the elements in a vector like this (in this case, all the colours) and a getValue(int index) method, which allows you to retrieve an object at a specific index.
You can try this:
Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 3);
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(combination.getValue(0)); // This gets the first value from the vector
System.out.println(combination.iterator().next()); // This is another way to do it
}
Check the Javadoc for details.
Perhaps this will work well for you:
// Print all possible combinations
for (ICombinatoricsVector<String> combination : gen) {
System.out.println(Arrays.toString(combination.toArray()));
}