验证字符串

时间:2015-12-14 01:47:27

标签: java validation while-loop

 */
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

我需要验证字符串颜色只是蓝红色或黄色但我不完全确定如何将其设置为只有那些颜色

2 个答案:

答案 0 :(得分:2)

让你这样做

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);

答案 1 :(得分:0)

这应该这样做:

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!");

修改

哎呀... JRowan打败了我:)我应该刷新页面:/