|
Answer» Hello all!
I am currently trying to learn some Java, and ran across something.
Let's say I prompt a user to input Yes or No, but I WANT the program to "catch" if they input something else - like a typo, and prompt them to enter Yes/No again.
I know how to do this with positive/negative doubles/Int. (see code snappet below) but how would I do this with strings?
Code: [Select] { System.out.print( "\nEnter PAY rate: " ); PayRate = input.nextFloat(); if( PayRate > 0 ) Rate = true; else { System.out.print( "Number must be positive" ); } }
My starting code for the strings is this:
Code: [Select] {//Start Case Option Module System.out.print( "\nWill this case have Edge Casters" ); System.out.print( "\nEnter \"Yes\" or \"No\"" ); CasEdgeAns = input.nextLine(); if (CasEdgeAns.equalsIgnoreCase( "Yes" )) {//If yes condition start CasEdge = true; System.out.print( "\nCase will have edge casters." ); }//If yes condition end else if (CasEdgeAns.equalsIgnoreCase( "No" )) {//If no condition start CasEdge = false; System.out.print( "\nCase will not have edge casters." ); }//If no condition end //Something here like //if (CaseEdgeAns != Yes && CaseEdgeAns != No) //System.out.print( "\nPlease enter \"Yes\" or \"No\" );
}//End case option module
Ideally, I want it to prompt the user to enter either yes or no, and will not continue until done so (I will probably need a boolean for a do...while statement for that block, I GUESS?).
Any help or hints would be greatly appreciated, thanks! This whole thing is a big work in progress so I can post the full code if needed. Thanks!Since from the looks of it you will be doing quite a few prompts like this it would make sense to make it a separate method, like so:
Code: [Select]import java.io.InputStream; import java.io.OutputStream; import java.util.Scanner; import java.util.stream.Stream;
public class BoolSelect {
/** * @param args the command LINE arguments */ public STATIC void main(String[] args) { boolean result = PromptChoice(); System.out.println("Selection was:" + result); } public static boolean PromptChoice(){ Scanner s = new Scanner(System.in); boolean foundresult = false; while(!foundresult){ System.out.print("Enter your choice (Y/N):"); String sread = s.nextLine(); if(sread.equalsIgnoreCase("Y")) return true; if(sread.equalsIgnoreCase("N")) return false; System.out.println("Invalid Choice."); } System.out.println(); return false; //this code is hueristically unreachable but the compiler complains... } } Thank you for you help again! Haha you are the best ^.^
|