0

I want my program to only accept string and prompt a message if the user input is invalid.

import java.util.Scanner;
public class Details{

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String lastname;
        String firstname;
        String middlename;

        System.out.print("Enter Number of passenger : ");
        int passenger = input.nextInt(); 

        for(int x = 0 ; x < passenger ; x++){
            do{
                System.out.print("\nEnter Lastname  :");
                lastname = input.nextLine().trim();

                if(lastname.equals("") || lastname.equals(" "))
                {                 
                    System.out.print("\nEnter Neccessary Details");               
                }
            } while(lastname.isEmpty());

            do{
                System.out.print("\nEnter Firstname : ");
                firstname = input.nextLine();

                if(firstname.equals("") || firstname.equals(" "))
                {
                    System.out.print("\nEnter Neccessary Details");    
                }
            } while(firstname.isEmpty());

            do{
                System.out.print("\nEnter Firstname : ");
                middlename = input.nextLine();

                if(middlename.equals("") || middlename.equals(" "))
                {
                    System.out.print("\nEnter Neccessary Details");    
                }
            }while(middlename.isEmpty());

        }//end of forloop

    }
}

i already try this code, at first it works but it shows logical error in the long run. And give me an output something like this.

    sample output
    Enter Firstname  : // the problem is, it seems has already have an input
    Enter Neccessary Details
    Enter Firstname  :

so how can i fix this? is there an alternative way to validate string input? please keep it simple i am just a beginner thanks

  • 1
    Can you show the entire Java class? –  Feb 08 '20 at 13:14
  • sorry about that, i edited it – Smile Kenny Feb 08 '20 at 13:28
  • 1
    Could you please be more specific on where **specifically** you get errors? What is the input and what error do you get exactly? – HimBromBeere Feb 08 '20 at 13:37
  • 1
    You seem to want to create multiple passengers, not just one. So you surely need multiple `lastName` and `firstName`. So create a class `Passenger` which has a first- and a lastname. Then use a `List` and create a new `Passenger` on every iteration of the outer loop. – HimBromBeere Feb 08 '20 at 13:43

4 Answers4

0

You can use trim() method to remove all spaces at the beginning and at the end of string and then check if it is empty:

firstname = input.nextLine().trim();

EDIT: This code seems to work as you need:

import java.util.Scanner;

public class Details {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String lastname;
        String firstname;
        String middlename;

        System.out.println("Enter Number of passenger : ");
        int passenger = input.nextInt();
        input.nextLine();

        for (int x = 0; x < passenger; x++) {
            do {
                System.out.println("Enter Lastname  :");
                lastname = input.nextLine().trim();
                if (lastname.isEmpty()) {
                    System.out.println("\nEnter Neccessary Details");
                }
            } while (lastname.isEmpty());

            do {
                System.out.println("Enter Firstname : ");
                firstname = input.nextLine().trim();
                if (firstname.isEmpty()) {
                    System.out.println("\nEnter Neccessary Details");
                }
            } while (firstname.isEmpty());

            do {
                System.out.println("Enter Middlename : ");
                middlename = input.nextLine().trim();
                if (middlename.isEmpty()) {
                    System.out.println("Enter Neccessary Details");
                }
            } while (middlename.isEmpty());
        }
    }
}

The main change here is that I replaced System.out.print with System.out.println. System.out.print somehow prints only after following input.nextLine() read is finished (System.out.flush right after printing does not work), so it seems that you press Enter button at the start of your input, and that empty line is read by Scanner. Also I added input.nextLine() line right after reading passenger count, so Scanner goes to the next line after reading that number.

ardenit
  • 3,070
  • 5
  • 16
0

Because the Scanner.nextInt method does not read the newline character in your input, you need to consume the line after nextInt:

int passenger = input.nextInt();
input.nextLine();

This will solve the it seems it already has an input problem.

See this for details.

0

The Scanner seems to have problems due using the same one in multiple whiles. Try using the Scanner in a method like here:

public String getInput () {

Scanner sc = new Scanner(System.in);
return sc.nextLine(); 
}

And then use

firstname = getInput();
niklascube
  • 31
  • 3
0

You seem to want to create multiple passengers, not just one. So you surely need multiple lastName and firstName. So create a class Passenger which has a first- and a lastname. Then use a List<Passenger> and create a new Passenger on every iteration of the outer loop.

So you shoul dhave this:

class Passenger {
    String lastname;
    String firstname;
    String middlename;
}

Now within your main you need a List<Passenger>:

List<Passenger> passengers = new ArrayList<>();

Now I would suggest to extract a single method from your three do-while-loops, in order to have a single validation-method:

String getInput(String kind) {
    String result;
    do{
        System.out.print("\nEnter " + kind + " : ");
        result = input.nextLine().trim();
    } while(result.isEmpty());
}

Finally put that into your loop within main and create a new Passenger on ever iteration, as mentioned above:

static void main(String[] args) {
    List<Passenger> passengers = new ArrayList<>();
    Scanner input = new Scanner(System.in);

    System.out.print("Enter Number of passenger : ");
    Integer numPassengers = input.nextInt(); 

    for(int x = 0; x < numPassengers; x++){
        String firstName = getInut("FirstName");
        String lastName = getInput("LastName");
        String MiddleName = getInput("MiddleName");
        passengers.add(new Passenger(firstName, lastName, middleName);
    }
}

Of course you need a constructor for your Passenger-class that accepts three String-args. Furthermore you should never expose public fields as I did above, instead have a public get-method. So your class should look like this:

class Passenger {
    String firstName;
    String lastName;
    String middleName;

    public Passenger(String firstName, lastName, middleName) { // constructor
        this.firstName = firstName;
        this.lastName = lastName;
        this.middleName = middleName;
    }

    public String getFirstName { return this.firstName; }
    public String getLastName { return this.lastName; }
    public String getMiddleName { return this.middleName; }
}
HimBromBeere
  • 32,045
  • 4
  • 46
  • 84