Skip to content
Advertisement

How to keep looping through until user has inputted string of valid length?

I am trying to write a program which takes the user input and then checks to see if it is equal to or less than five characters. Then if it meets this condition we store the name, else we keep asking for their name until the condition is met.

I tried doing this using a while loop but I don’t know how to incorporate the question of asking their name in. Please see my code below:

import java.util.*;

public class Main {
    public static String newName;
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = scanner.nextLine();
        while (name.length() <= 5){
            newName = name;
            break;
        }
       // ELSE PRINT PLEASE INPUT VALID NAME
        System.out.println("Your name is: " + newName);
    }
}

Essentially I want ask for the user’s name and store it in another variable IF and ONLY IF it is less than or equal to 5 characters. Otherwise I want to loop through and ask them again “Enter your name”

So for example: Jack Smith are valid but then Jackson Samuel are not and I literally want to do System.out.println("Enter your name:"); and repeat the process till they input a name with correct string length

Would be really great if someone could help me here.

Thanks.

Advertisement

Answer

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name;

        while(true) {
            System.out.println("Enter your name");
            name = scanner.next();

            if(name.length() <= 5) break;
        }
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement