1

I'm currently working my way through a Udemy Java course and am practicing what i have learnt thus far.

I have the following simple program which i am planning on using to get the user to input his name.

import java.util.Scanner;



public class Adventure {
    public static final int menuStars = 65;
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        String firstName = "";
        String lastName = "";
        boolean validName = false;
        while(!validName){
            //Entering first name
            System.out.println("Please enter your first name.");
            try {
                firstName = input.nextLine();
                if(firstName.length() == 0){
                    throw new Exception("Please enter a first name of at least 1 character.");  
                }else{
                    //Entering last name
                    System.out.println("Please enter your last name.");
                    lastName = input.nextLine();
                    if(lastName.length() == 0){
                        throw new Exception("Please enter a last name of at least 1 character");
                    }else{
                        System.out.println("You have entered " + firstName +" " + lastName);
                    }

                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
                continue;
            }
            //Used to terminate loop when both first & last names are valid
            validName = true;
        }


    }
}

I want to make the program repeat the error message when the user inputs a blank name instead of restarting the entire program from the beginning.

E.g When the user enters a blank first name, i want the program to keep repeating "Please enter a first name of at least 1 character" and when the user enters a blank last name, for it to keep repeating "Please enter a last name of at least 1 character" until the user enters a valid name.

However, currently when the user enters a blank first name or last name, my program will repeat itself from the very beginning instead of repeating just the error message.

How would i go about making the program repeat just the error message?

Kenneth .J
  • 1,433
  • 8
  • 27
  • 49
  • why do you use try/catch? do you want to use them or you just want to see how they work? – Skaros Ilias Jun 07 '15 at 16:50
  • If I understand right, your continue is taking you up to the beginning of the while loop, which is what you want. Generally in a program like this the appropriate way to do it would be to repeat the question, but I guess if you don't want to do that you could take the question out of the loop, and use an empty print. – mcraenich Jun 07 '15 at 16:51
  • @SkarosIlias I read that the try catch loop should be used when i have a way of handling an exception. As such, shouldnt i be using a try catch loop as i am planning on repeating the question? – Kenneth .J Jun 07 '15 at 17:06

3 Answers3

1

Use a boolean variable that stores true when "Please enter your first name." is printed. Check before printing this string each time if this variable is false or not. Also, initialize it to false before the loop. Same idea goes for last name.

if(!printed)
{
  System.out.println("Please enter your first name.");
  printed=true;
}
skrtbhtngr
  • 2,223
  • 23
  • 29
1

havent tested that but i am guessing it can be like that, with out try/catch though, it just makes no sense to me using it in the way you have it on your code

String firstName = "";
String lastName = "";
System.out.println("Please enter your first name.");
firstName = input.nextLine();
while(firstName.length<1){
   System.out.println("Please enter a first name of at least 1 character.");
firstName = input.nextLine();
   }
lastName=input.nextLine();
while(firstName.length<1){
    System.out.println("Please enter a last name of at least 1 character.");
    lastName = input.nextLine();
}
System.out.println("You have entered " + firstName +" " + lastName);

Edit, some basic info about exceptions try catch is used when something unexpected happens and you try to find a way round it. for example if an array of 10 positions is expected at some point and a smaller array (lets say 4 positions) is being used. Then this would cause an exception causing the program to terminate with no further information.

With try catch you can check what the problem is, and try to either inform the user to do something(if they can) or close the program in a better way, using System.exit() for example and saving all the work that was done till that point

An other example is that if you ask for 2 numbers to do an addition. if the user enters letters instead of number the int sum=numbA+numbB; would throw and exception. This of course could be handled using an if. but even better would be something like this

Community
  • 1
  • 1
Skaros Ilias
  • 1,008
  • 12
  • 40
  • I read that the try catch loop should be used when i have a way of handling an exception. As such, shouldnt i be using a try catch loop as i am planning on repeating the question? If not, how should i be using try/catch in any piece of code? – Kenneth .J Jun 07 '15 at 17:08
0

A whitespace is actually considered a character, so the check of (length == 0) doesn't work for your purposes.

Although the following code below is incomplete (ex: handles the potentially undesirable case of firstname=" foo", (see function .contains()), it does what the original post asks - when the user enters a blank first/last name, it keeps repeating "Please enter a first/last name of at least 1 character" until the user enters a valid first/last name.

import java.util.Scanner;

public class Adventure {
    public static final int menuStars = 65;
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        String firstName = "";
        String lastName = "";

        boolean firstNameLegal = false;
        boolean lastNameLegal = false;

        // Entering first name
        while (!firstNameLegal) {
            System.out.println("Please enter your first name.");
            firstName = input.nextLine();

            if (!firstName.equals(" "))
                firstNameLegal = true;
            else
                System.out.println("Please enter a first name of at least 1 character.");  
        }

        // Entering last name
        while(!lastNameLegal){
            System.out.println("Please enter your last name.");
            lastName = input.nextLine();

            if(!lastName.equals(" "))
                lastNameLegal = true;
            else
                System.out.println("Please enter a last name of at least 1 character.");
        }

        System.out.println("You have entered " + firstName +" " + lastName);
    }
}
mcw
  • 50
  • 5