如何获得五种颜色输入的序列.颜色应该只有红色,绿色和蓝色需要一个图案的颜色.用Java编程



我需要额外的颜色循环吗?全部问题是一位设计师正试图用三种颜色创造一种新的五条纹图案。下表中提到了这些颜色及其代码。颜色字符代码红色R绿色G蓝色B设计师必须记住,没有两个相邻的条纹是相同的颜色。例如,RRGBR是一个无效的模式,但RGBRB是有效的。编写一个程序,接受设计师输入的五种颜色的序列来形成图案。在设计师进行的每一次选择中,程序都应该检查输入是否来自可用的颜色集。此外,程序应该检查相邻的颜色是否不相同。最后,程序应该显示创建的最终条纹图案。

public class Colors {
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter your Input.");
String color;
int counter = 0;
do {
color = scannerObject.next();
System.out.println("Your selection is :" + color);
counter++;
} while (counter < 5);
scannerObject.close();
}
}
  1. 您可以使用一个数组(例如,下面给出的代码中的desiredCombination[](来存储有效输入
  2. 您可以有一个List(例如,下面给出的代码中的List<String> allowedColors(或允许的颜色数组,您需要用它来验证输入颜色

按如下操作:

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
String color;
int counter = 0;
List<String> allowedColors = List.of("R", "G", "B");
String[] desiredCombination = new String[5];
do {
System.out.print("Enter a color [R/G/B]: ");
color = scannerObject.nextLine();
// There is no element before desiredCombination[0] and therefore the colour for
// desiredCombination[0] does not require comparing with the one before it.
if (counter == 0 && allowedColors.contains(color.toUpperCase())) {
desiredCombination[counter++] = color;
} else if (allowedColors.contains(color.toUpperCase()) && !color.equals(desiredCombination[counter - 1])) {
desiredCombination[counter++] = color;
}
} while (counter < 5);
System.out.println("The desired combination is: " + Arrays.toString(desiredCombination));
}
}

样本运行:

Enter a color [R/G/B]: R
Enter a color [R/G/B]: R
Enter a color [R/G/B]: G
Enter a color [R/G/B]: B
Enter a color [R/G/B]: R
Enter a color [R/G/B]: R
Enter a color [R/G/B]: B
The desired combination is: [R, G, B, R, B]

一个重要的注意事项:永远不要为System.in关闭Scanner,因为它也会关闭System.in,您将无法再次打开它。

相关内容

最新更新