Search code examples
javastringerror-checking

Checking empty string not working in loop


Hi I am new to programming and java. The below code is going to be adding the user inputs into a file which I have not implemented yet. However,

I don't know why:

  • The checking of the empty string (the displaying of the 'Error. Please enter a name.' message) only works when the outer do-while loop is not present, but the checking of the time works.
  • I also put the name = ""; time = -1.0; at the start of the do-while loop again to restart the variables since the input for the name would get skipped over since it has a string already from the first time the code is run, but is there another way to restart the variables properly or to improve my empty string checking so i don't have to do this roundabout method?

Would appreciate any help.

package so;

import java.util.Scanner;

public class programTest {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String name = "";
    double time = -1.0;
    char moreDataChoice = 'a';
    boolean moreData = true;

    do {
      name = "";
      time = -1.0;

      System.out.println("Name:");
      while (name.isEmpty() == true) {
        name = sc.next();

        if (name.isEmpty() == false) {
          break;
        } else {
          System.out.println("Error. Please enter a name.");
        }
      }

      System.out.println("Time:");
      do {
        time = sc.nextDouble();
        sc.nextLine();
        if (time > 0) {
          break;
        } else {
          System.out.println("Error. Please enter a appropriate time");
        }
      } while (time < 0.0);

      System.out.println("Enter more data? (y/n)");
      do {
        moreDataChoice = sc.next().charAt(0);


        if (moreDataChoice == 'y') {
          moreData = true;
        } else if (moreDataChoice == 'n') {
          moreData = false;
          break;
        } else {
          System.out.println("Error. Please enter y or n.");
        }

      } while ((moreDataChoice != 'y') && (moreDataChoice != 'n'));
    } while (moreData == true);
    sc.close();
  }
}
  • The checking of the empty string (the displaying of the 'Error. Please enter a name.' message) only works when the outer do-while loop is not present, but the checking of the time works.
  • I also put the name = ""; time = -1.0; at the start of the do-while loop again to restart the variables since the input for the name would get skipped over since it has a string already from the first time the code is run, but is there another way to restart the variables properly or to improve my empty string checking so i don't have to do this roundabout method?

Solution

  • The below code uses separate methods for obtaining the name and the time – just to show you a different way to code your program.

    Note that method nextDouble, in class Scanner, will throw InputMismatchException if the entered value cannot be parsed to a double. Beginner programmers tend to assume that user-entered values will always be valid. Nonetheless, you should always add code that handles invalid input. Also, InputMismatchException is an unchecked exception which means it doesn't need to be explicitly handled, but it can be. Consequently, you may want to re-consider what constitutes a valid name – apart from it not being empty. Currently any sequence of characters is a valid name, for example $#3.14?

    Lastly, after calling method nextDouble and before calling method nextLine, you need to add [another] call to method nextLine. Refer to this SO question to understand why.

    Here is the code:

    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class ProgTest {
    
        private static String getName(Scanner sc) {
            String name;
            do {
                System.out.print("Name: ");
                name = sc.nextLine();
                if (name.isEmpty()) {
                    System.out.println("You did not enter a name.");
                }
            } while (name.isEmpty());
            return name;
        }
    
        private static double getTime(Scanner sc) {
            double time;
            do {
                System.out.print("Time: ");
                try {
                    time = sc.nextDouble();
                }
                catch (InputMismatchException xInput) {
                    time = 0.0;
                }
                if (time <= 0.0) {
                    System.out.println("Enter a positive number (which may include a decimal fraction).");
                }
                sc.nextLine();
            } while (time <= 0);
            return time;
        }
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String choice;
            do {
                String name = getName(sc);
                double time = getTime(sc);
                System.out.printf("Received: %s %f%n", name, time);
                System.out.print("Enter more data? (y/n): ");
                choice = sc.nextLine();
            } while ("y".equalsIgnoreCase(choice));
        }
    }
    

    Here is output from a run of the above code:

    Name: 
    You did not enter a name.
    Name: George
    Time: d
    Enter a positive number (which may include a decimal fraction).
    Time: 0
    Enter a positive number (which may include a decimal fraction).
    Time: 5.9
    Received: George 5.900000
    Enter more data? (y/n): y
    Name: Diego
    Time: 10
    Received: Diego 10.000000
    Enter more data? (y/n): n