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

i need to validate string color to only be blue red or yellow but im not exactly sure how to set it to only those colors

2 Answers 2

2

make your do while like this

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);
Sign up to request clarification or add additional context in comments.

Comments

0

This should do it:

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

EDIT:

whoops...JRowan beat me to it :) I should have refreshed the page :/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.