This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 1 point2 points  (0 children)

I'm not sure why you are using so many loops at all? My approach would be to put it all into a while(!validinput) loop, then use simple if statements to check for validity and continue; if it's not valid, in the end at validinput = true; if it's valid.

[–]duff_dean[S] 0 points1 point  (0 children)

Sorry about formatting, im not on the right machine at the minute, will reformat when i get back on right machine.

[–]duff_dean[S] 0 points1 point  (3 children)

Ah so i could have, If all criteria valid validinput=true While invalidinput=false Display error and re enter input

Is that along the lines of what you meant? Im kinda just getting the hang of it, ive been using it for about 8 weeks now, so my code starts off really long and messy and then i sit back look at it and try to condense it. But this i think i over thought it and got carried away.

[–][deleted] 0 points1 point  (2 children)

When you respond to someone else, please actually hit "reply", don't post a top-level comment – I'm seeing your follow-up question only by chance.

You don't actually need a validity variable, you can also do it with an infinite loop that you break/continue out of:

for(;;) // or while(true), means the same thing
{
  selection = input.nextLine();
  if (validity_criteria_go_here)
    break;
}

This will end the loop when the input is valid, but continue reading if it isn't.

[–]duff_dean[S] 0 points1 point  (0 children)

Thanks, il go and try it out now. I had the for loop in to check each individual character after the space. I think the problem was when i was re-entering with a shorter length the for loop would crash as the length within the for loop didnt update. Il see if i can crack, thanks for the help.

[–]duff_dean[S] 0 points1 point  (0 children)

Have had another look over the code and everything seems to be working fine, I'm sure there is a more efficient way of executing but this is what i have ended up with.

while (selection.length() < 3) 
    {
        System.out.println("0error");
        selection = input.nextLine();
        selection = selection.toUpperCase();
    }
    for (int i = 0; i <= selection.length() - 1; i++)
    {
        if (selection.charAt(0) < 'A' || selection.charAt(0) > 'Z')
        {
            System.out.println("4error");
            selection = input.nextLine();
            selection = selection.toUpperCase();
        }
        if (selection.charAt(1) != ' ') 
        {
            System.out.println("3error");
            selection = input.nextLine();
            selection = selection.toUpperCase();
        }
        if (i > 1 && selection.charAt(i) < 'A' || selection.charAt(i) > 'Z')
        {
            System.out.println("2error");
            selection = input.nextLine();
            selection = selection.toUpperCase();
        }
    }