1

Pretty basic question I believe... lets say I had this program and the access code had to specifically be 13 characters long. How would I make it so that if it wasn't 13 long then the user would have to retry and enter it again?

import java.util.Scanner;
public class access code
{
   Scanner scan;

    public void go()
    {
        String code = ("Enter your access code: ");

    }
}
ANON
  • 75
  • 1
  • 9
  • Have you tried anything? Are you familiar with String.length()? – nhouser9 Feb 26 '17 at 22:57
  • I did some research but that only seems to tell me how long the string is.. it doesn't set the exact amount it can be – ANON Feb 26 '17 at 23:46
  • And you can't think of any way to combine an `if` statement with `.length()` to force the user to enter the length you want? – nhouser9 Feb 26 '17 at 23:51
  • well I tied String isbn = ("Enter the book's ISBN: "); if (isbn.length /= 13) isbn = ("Enter the book's ISBN: "); and I get a can't find symbol error. Im sorta new to java and that's the way I would do it in python which im much better at – ANON Feb 26 '17 at 23:59
  • also pretend those statements are on separate lines idk how to make it look like that in comments – ANON Feb 27 '17 at 00:00
  • You need to use the scanner to get the input, not just set `String isbn = "enter isbn";`. I suggest you read a simple tutorial on taking input and on how to do basic operations before asking – nhouser9 Feb 27 '17 at 00:02

1 Answers1

0

Per request, here's some explanation as to why this works. You need to repeatedly ask for information until the user enters something consisting of 13 characters. This code gets user input while the length of input is not 13. Which means that the loop terminates when the length is 13.

String input = "";
while (input.length() != 13){
    System.out.print("Enter code: ");
    input = scan.nextLine();
}
Neatname
  • 124
  • 6
  • I thought that this question and answer were simple enough to not warrant an explanation. But I added an explanation in case someone somehow can't understand what's happening here. – Neatname Feb 27 '17 at 01:11