0

How can i handle a user entering a String in each of these methods below. I have tried many times using different suggestions and the error keeps looping infinitely. How can i force a user to enter an int instead of a string by adding to the methods below and not modifying them in their present state.

    private void readMonth(Scanner keyboardIn)
    {
        boolean success = false;
        while(!success)
        {   
            try
            {
                System.out.print("Enter the month the account opened: ");
                int m = keyboardIn.nextInt();
                dateOpened.setMonth(m);
                success = true;
            }catch(Exception e)
            {
                System.out.println(e.getMessage());
            }   
          } 
       }    


    // Enter the year, checking for errors
    private void readYear(Scanner keyboardIn)
    {
        boolean success = false;
        while(!success)
        {   
            try
            {
                System.out.print("Enter the year the account opened: ");
                int y = keyboardIn.nextInt();
                dateOpened.setYear(y);
                success = true;
            }catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
    }
TimeToCode
  • 821
  • 2
  • 12
  • 28
Daniel
  • 29
  • 8

2 Answers2

1

When you try to enter any character except numbers, idValidationfunction will return false. I also printed returns out, so you can easily understand how it worked.

import java.util.Scanner;

public class Daniel {
    private static Scanner sc;

    private static boolean idValidation(String id) {
        try {
            Integer.parseInt(id);
            System.out.println("return true");
            return true;
        } catch (NumberFormatException e) {
            System.out.println("return false");
            return false;
        }
    }

      private static void readMonth(Scanner keyboardIn)
        {
            boolean success = false;
            while(!success)
            {   
                try
                {
                    System.out.print("Enter the month the account opened: ");
                    String m = keyboardIn.nextLine();
                    if(!idValidation(m)){
                        return;
                    }
//                  dateOpened.setMonth(m);
                    success = true;
                }catch(Exception e)
                {
                    System.out.println(e.getMessage());
                }   
              } 
           }    


        // Enter the year, checking for errors
        private static void readYear(Scanner keyboardIn)
        {
            boolean success = false;
            while(!success)
            {   
                try
                {
                    System.out.print("Enter the year the account opened: ");
                    String y = keyboardIn.nextLine();
                    if(!idValidation(y)){
                        return;
                    }

//                  dateOpened.setYear(y);
                    success = true;
                }catch(Exception e)
                {
                    System.out.println(e.getMessage());
                }
            }
        }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        readMonth(sc);
        readYear(sc);
    }
}
Alican Balik
  • 1,166
  • 1
  • 7
  • 20
  • Can you take my method of readYear() or readMonth() and show me how with the suggestion above. – Daniel Nov 08 '16 at 19:37
  • I will do it when l get home. – Alican Balik Nov 08 '16 at 20:17
  • Would you get a chance to have a look at that today? – Daniel Nov 09 '16 at 12:10
  • Done. Try to debug the code in order to understand it. – Alican Balik Nov 09 '16 at 14:31
  • You see its in a class called Current and the Tester for it is called CurrentFileTester. There is also a CurrentFileHandler and a Menu , Date and Name class. The read() method is in the Current class. – Daniel Nov 09 '16 at 23:49
  • It is working but its still not doing what it should. I also have a setDay method in Date class which sets the day. I see it is commented out here above. There is also one called setMonth(), setYear(). Is there anything i can do within the Date class within the methods there that may not allow a user to enter the input wrong? I can show you the Date class – Daniel Nov 09 '16 at 23:49
  • // Initialisation constructor public Date(int d, int m, int y) throws IllegalArgumentException { if(day <= 0 || day > 31 || month < 0 || month > 12 || year 1900) throw new IllegalArgumentException("DATE IS INVALID"); { this.day = d; this.month = m; this.year = y; } } – Daniel Nov 09 '16 at 23:57
  • You can check the input value for setMonth with if statement. You can check if input is between 1 and 12. – Alican Balik Nov 10 '16 at 10:59
0

Demo Code

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class ReadDateFromKeyboard {

    private static final int NUM_OF_PARAMS = 3;
    private static final int DAY = 0;
    private static final int MONTH = 1;
    private static final int YEAR = 2;

    private static final String DAY_MESSAGE  = "Enter the day the account opened: ";
    private static final String MONTH_MESSAGE = "Enter the month the account opened: ";
    private static final String YEAR_MESSAGE  = "Enter the year the account opened: ";

    public static void main(String[] args) {
        Scanner keyboardIn = new Scanner(System.in);
        int[] params = new int[NUM_OF_PARAMS];

        readDay(keyboardIn, params);
        readMonth(keyboardIn, params);
        readYear(keyboardIn, params);

        Date date = getDate(params);

        String pattern = "dd-MM-yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        System.out.println("\nDate: " + sdf.format(date));

        keyboardIn.close();
    }

    private static void readDay(Scanner keyboardIn, int[] params) {
        genericRead(DAY_MESSAGE, keyboardIn, params, DAY);
    }

    private static void readMonth(Scanner keyboardIn, int[] params) {
        genericRead(MONTH_MESSAGE, keyboardIn, params, MONTH);
    }

    private static void readYear(Scanner keyboardIn, int[] params) {
        genericRead(YEAR_MESSAGE, keyboardIn, params, YEAR);
    }

    private static void genericRead(String message, Scanner keyboardIn, int[] params, int paramType) {
        boolean success = false;
        while (!success) {
            try {
                System.out.print(message);
                params[paramType] = keyboardIn.nextInt();

                success = true;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public static Date getDate(int[] params) {
        return getDate(params[0], params[1], params[2]);
    }

    private static Date getDate(int day, int month, int year) {
        Calendar c = Calendar.getInstance();

        c.set(year, month - 1, day, 0, 0);

        return c.getTime();
    }
}

Demo Output

Enter the day the account opened: 24
Enter the month the account opened: 1
Enter the year the account opened: 1982

Date: 24-01-1982
Levent Divilioglu
  • 9,139
  • 5
  • 49
  • 96