0

The following is my code. The code works fine with the 'save' and 'search' menus. However, after I 'delete' a person and select the next menu as 'search', the program skips the part where the user enters a name, thus showing "no results found" as the result.

I thought that the \n may be the problem and tried parseInt(), System.out.flush(), and using nextLine() as written in the comments in the code but they all seemed not to work.

Also, I am confused why in some cases, even though there is a \n left in the buffer, I can enter the 'name' without the program skipping.

Please let me know if the \n is not the cause of the problem. Thank you for your time.

import java.util.Scanner;

class PhoneInfo
{
    String name;
    private String phoneNumber;
    private String birthDay;
    private String birthYear;
    private int choice;

    public PhoneInfo(String name, String phoneNumber, String birthDay)
    {
        this.name = name;
        this.phoneNumber = phoneNumber;
        this.birthDay = birthDay;
    }

    public PhoneInfo(String name, String phoneNumber, String birthDay, String birthYear)
    {
        this(name, phoneNumber, birthDay);
        this.birthYear = birthYear;
    }

    public void showPhoneInfo()
    {
        System.out.println("name: " + name);
        System.out.println("phone no.: " + phoneNumber);
        System.out.println("birthday: " + birthDay);
        if(birthYear == null)
            System.out.println("birth year: no record");
        else
            System.out.println("birth year: " + birthYear);

        System.out.println("-----------------------------");
    }
} 

class Manager //save, search, delete data
{
    PhoneInfo[] pBook = new PhoneInfo[100];
    Scanner input = new Scanner(System.in);

    public PhoneInfo inputData()
    {   
        System.out.print("name: ");
        String name = input.nextLine();

        System.out.print("phone no.: ");
        String phoneNumber = input.nextLine();

        System.out.print("birthday: ");
        String birthDay = input.nextLine();

        System.out.print("birth year: ");
        String birthYear = input.nextLine();

        PhoneInfo pData = new PhoneInfo(name, phoneNumber, birthDay, birthYear);

        System.out.println("-----------------------------");

        return pData;
    }

    public void saveData()
    {   
        for(int i=0; i<100; i++)
        {
            if(pBook[i] == null)
            {   
                pBook[i] = inputData(); //new entry
                break;
            }
            else
            {
                if(i == 99)
                    System.out.println("database full");
                else
                    continue;
            }
        }
    }

    public void searchData()
    {
        System.out.print("name: ");
        //tried putting System.out.flush(); here as well... didn't work
        String name = input.nextLine(); // do not want to use input.next() if possible
        System.out.println("\nSearching data...\n");
        for(int i=0; i<100; i++)
        {
            if(pBook[i] != null)
            {
                if(pBook[i].name.equals(name))
                {
                    pBook[i].showPhoneInfo();
                        break;
                }
                else
                    continue;
            }
            else
            {
                System.out.println("no results found");
                break;
            }
        }
    }

    public void deleteData()
    {
        int idx;
        System.out.print("name: ");
        String name = input.nextLine();

        idx = getIndex(name);
        if(idx == -1)
            System.out.println("no matching name");

        System.out.println("Are you sure you want to delete " + name + "?");
        System.out.print("1. yes\n2. no\n> ");
        int choice = input.nextInt();
        if(choice == 1)
        {   
            for(int i=idx; i<99; i++)
                pBook[i] = pBook[i+1];
            System.out.println(name + " deleted...");
            System.out.println("-----------------------------");
        }
        if(choice == 2)
            return;
    }

    public int getIndex(String name)
    {
        int index = -1;
        for(int i=0; i<100; i++)
        {   
            if(pBook[i] != null)        
                if(pBook[i].name.equals(name)) //error --> worked when I added if(pBook[i] != null). why?? what difference did it make?
                    index = i;
                else
                    continue;
            else
                continue;
        }
        return index;
    }
}

class PhoneBookVer3
{
    static Scanner input = new Scanner(System.in);

    public static void showMenu()
    {
        System.out.println("[MENU]");
        System.out.println("choose...");
        System.out.println("1. save data");
        System.out.println("2. search data");
        System.out.println("3. delete data");
        System.out.println("4. exit program");
        System.out.print("> ");
    }

    public static void main(String[] args)
    {
        PhoneBookVer3 pb = new PhoneBookVer3();
        int choice;
        Manager mng = new Manager();
        while(true)
        {
            pb.showMenu();
            //choice = Integer.parseInt(input.nextLine()); // why this doesn't work either..
            choice = input.nextInt();
            //input.nextLine(); //why this doensn't consume the \n???

            switch(choice)
            {
                case 1:
                    System.out.println("-----------------------------");
                    mng.saveData();
                    break;
                case 2:
                    System.out.println("-----------------------------");
                    mng.searchData();
                    break;
                case 3:
                    System.out.println("-----------------------------");
                    mng.deleteData();
                    break;
                case 4:
                    System.out.println("-----------------------------");
                    System.out.println("end of program");
                    return;
            }
        }
    }
}
asdfqwer
  • 5
  • 2
  • @RussianVodka Um, does this have to do with my question?? – asdfqwer Nov 22 '14 at 01:09
  • possible duplicate of [Skipping nextLine() after use nextInt()](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) – Tom Nov 22 '14 at 01:09
  • @Tom I've already seen that page and I was trying to solve this problem using what I've learned. Using exception handlers are further back in the book that I'm using. If you've read the bold text I wrote above, I tried the thing in the post you mentioned. But they all didn't work – asdfqwer Nov 22 '14 at 01:12
  • You'e calling `input.nextInt();` in the delete method. Since there are no comments there, you haven't tried anything else there, right? Try to do so. At the end, this is still a duplicate of the mentioned question. You've just changes the wrong line. – Tom Nov 22 '14 at 01:23
  • @Tom oh i see, Thank you – asdfqwer Nov 22 '14 at 01:31
  • To avoid problems like that, you could read words the decisions. For example like this: `if (input.equalsIgnoreCase("yes")) { /* user entered "yes" */ }`. [JavaDoc of #equalsIgnoreCase()](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase%28java.lang.String%29). – Tom Nov 22 '14 at 01:35
  • @Tom A way to not use numbers and not deal with \n. That is an interesting way. Thank you. – asdfqwer Nov 22 '14 at 01:45

2 Answers2

0

In your method public void deleteData(), you need to do:

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

The last nextLine() will consume the \n that nexInt() is leaving.

Maybe it will be better that you use parseLine() more often and convert String to int when necessary.

JosEduSol
  • 4,768
  • 3
  • 19
  • 29
  • Is using parseLine() rather than input.nextLine() considered better programming? – asdfqwer Nov 22 '14 at 01:30
  • @asdfqwer Well, what behaviour do you expect when `choice` it's not a number?. If it is not, you will have an exception. – JosEduSol Nov 22 '14 at 01:34
  • @asdfqwer Moreover, the answer you accepted suggest as alternative to convert the input to int without consider that this may fail and throw an exception. – JosEduSol Nov 22 '14 at 01:40
  • oh I didn't know that since I didn't learn exceptions yet and I am only using notepad and console to program. And as for the alternative answer, I don't quite understand yet but I think I will keep your suggestion in mind when learning exceptions. Thank you. – asdfqwer Nov 22 '14 at 05:30
0

The problem is that you are reading choice using the input.nextInt(). When you do that nextInt() will only read the integer and the newline character you enter will be read by the next nextLine() so to prevent this you can add a dummy input.nextLine() after the input.nextInt()

Code

System.out.println("Are you sure you want to delete " + name + "?");
System.out.print("1. yes\n2. no\n> ");
int choice = input.nextInt();
input.nextLine(); // to read the newline character 

Alternate method

Another method is to read the choice using nextLine() itself and then convert the input to int.

int choice = Integer.parseInt(input.nextLine());
Community
  • 1
  • 1
Johny
  • 2,003
  • 3
  • 17
  • 31