简体   繁体   中英

Why isn't my println working?

The program isn't printing out the thanks (name). Instead, the line is being skipped completely, looping back to the main menu. Can someone please explain why? It should be creating a new string based on the indexes indicated and storing the result in 'firstName' then printing it out as "Thanks (name)!"

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    String[] custInfo = new String[20];

    String MANAGERID = "ABC 132";
    String userInput;
    String cust = "Customer";
    String pts = "Print to screen";
    String exit = "Exit";
    int counter = 0;
    int full = 21;
    boolean cont = true;

    while(cont) {

        System.out.println("Enter the word \"Customer\" if you are a customer or your ID if you are a manager.");
        userInput = in.nextLine();

        if (userInput.equalsIgnoreCase(exit)) {
            System.out.println("Bye!");
            System.exit(0);
        }

        try {
            if (userInput.equalsIgnoreCase(cust)) {
                System.out.println("Hello, please enter your name and DoB in name MM/DD/YYYY format.");
                custInfo[counter] = in.nextLine();
                String firstName=custInfo[counter].substring(0,(' '));
                System.out.println("Thanks "+firstName+"!"); 
                counter++;
            }

            if (counter==full) {
                System.out.println("Sorry, no more customers.");
            }
        } catch(IndexOutOfBoundsException e) {
        }
    }
}

Your code is generating an IndexOutOfBoundsException on the line below and jumping to the Exception handler code.

String firstName=custInfo[counter].substring(0,(' '));

String.substring is overloaded and has two definitions:

substring(int startIndex)
substring(int startIndex, int endIndex)

In Java, a char data type is simply a 16-bit number behind the scenes. It is converting ' ' (space) into 32 and will error on any String that is shorter than that (presuming counter is pointing to a valid index)

使用此代替custInfo[counter].indexOf(" ")获取名称和DoB之间的空间的索引:

String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM