public static char randomLetter() {
Random r = new Random();
char randomChar = (char) (97 + r.nextInt(26));
return randomChar;
}
public static Color randomColor(){
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
return randomColor;
}
我有这两种方法。一个字母返回一个随机字母,另一个返回一个随机颜色。
如何编辑这些方法,以便randomLetter()
只返回一次字母而不返回两个相同的字母?
如何让randomColor()
仅在RED
,YELLOW
,GREEN
或BLUE
之间返回随机颜色?
答案 0 :(得分:2)
随机选择可以包含重复项。如果你不想要重复,你想要的就是洗牌。
这是实现此目的的一种方法。
package com.ggl.testing;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ShuffleTest {
private static boolean shuffleLetters = true;
private static boolean shuffleColors = true;
private static int shuffleLetterIndex = 0;
private static int shuffleColorIndex = 0;
private static List<Character> letters = new ArrayList<>();
private static List<Color> colors = new ArrayList<>();
public static void main(String[] args) {
System.out.println(shuffleLetter());
System.out.println(shuffleLetter());
System.out.println(shuffleLetter());
System.out.println(shuffleColor());
System.out.println(shuffleColor());
System.out.println(shuffleColor());
}
public static char shuffleLetter() {
if (shuffleLetters) {
int start = (int) 'a';
int end = (int) 'z';
for (int i = start; i <= end; i++) {
letters.add(Character.valueOf((char) i));
}
Collections.shuffle(letters);
shuffleLetters = false;
}
return letters.get(shuffleLetterIndex++);
}
public static Color shuffleColor() {
if (shuffleColors) {
colors.add(Color.RED);
colors.add(Color.YELLOW);
colors.add(Color.GREEN);
colors.add(Color.BLUE);
Collections.shuffle(colors);
shuffleColors = false;
}
return colors.get(shuffleColorIndex++);
}
}
答案 1 :(得分:1)
改为使用TabCollection ipsTabs = new TabCollection();
ipsTabs.signHereTabs = new List<Tab>();
ipsTabs.signHereTabs.Add(new Tab()
{
documentId = 5,
anchorString = "soc1",
recipientId = "1",
xPosition = 100,
yPosition = 150
});
ipsTabs.signHereTabs.Add(new Tab()
{
documentId = 5,
anchorString = "soc2",
recipientId = "2",
xPosition = 100,
yPosition = 150
});
ipsTabs.initialHereTabs = new List<Tab>();
ipsTabs.initialHereTabs.Add(new Tab()
{
documentId = 5,
anchorString = "ci1",
recipientId = "1",
xPosition = -100,
yPosition = 150
});
ipsTabs.initialHereTabs.Add(new Tab()
{
documentId = 5,
anchorString = "ci2",
recipientId = "2",
xPosition = -100,
yPosition = 150
});
var tabstatus = template.AddTabs(ipsTabs);
:
enum