Java 验证字符串
我需要验证字符串颜色是否只有蓝红色或黄色,但我不确定如何将其设置为只有这些颜色Java 验证字符串,java,validation,while-loop,Java,Validation,While Loop,我需要验证字符串颜色是否只有蓝红色或黄色,但我不确定如何将其设置为只有这些颜色 */ package controller; import java.util.Scanner; /** * * @author dylan */ public class Controller { public Controller() { getUserInput(); }// end of controller private void getUserI
*/
package controller;
import java.util.Scanner;
/**
*
* @author dylan
*/
public class Controller {
public Controller() {
getUserInput();
}// end of controller
private void getUserInput() {
String color = "";
boolean isColor;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a primary color: blue, red, or yellow.");
color = input.nextLine();
do{
if (input.hasNextLine()) {
color = input.nextLine();
isColor = true;
}
else {
System.out.println("Thats not a primary color");
isColor = false;
}
}
while(!(isColor));
System.out.println(color);
}
}// end class
这应该做到:
do{
System.out.println("Please enter a primary color: blue, red, or yellow.");
color = input.nextLine();
if (color.equals("blue")|| color.equals("red") || color.equals("yellow")) {
isColor = true;
} else {
System.out.println("Thats not a primary color");
isColor = false;
}
}
while(!(isColor));
System.out.println(color);
编辑:
哇……JRowan比我快:)我应该刷新页面:/
String color = "";
Scanner input = new Scanner(System.in);
do{
System.out.println("Please enter a primary color: blue, red, or yellow or nothing to exit:");
color = input.nextLine().toLowerCase();
if ("blue".equals(color) || "red".equals(color) || "yellow".equals(color)) {
System.out.println("The color " + color + " is CORRECT!\n");
}
else {
if (!"".equals(color) ) {
System.out.println("WRONG - The color " + color + " is not a primary color!\n");
}
}
} while(!"".equals(color));
input.close();
System.out.println("Program Terminated!");