简体   繁体   English

为什么我的println不起作用?

[英]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)!" 它应该根据指示的索引创建一个新字符串,并将结果存储在“ firstName”中,然后将其打印为“谢谢(名字)!”。

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. 您的代码在下面的行上生成IndexOutOfBoundsException ,并跳转到Exception处理程序代码。

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

String.substring is overloaded and has two definitions: String.substring重载,并且具有两个定义:

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

In Java, a char data type is simply a 16-bit number behind the scenes. 在Java中, char数据类型只是幕后的16位数字。 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) 它将' ' (空格)转换为32,并且任何短于该字符串的String都会出错(假定计数器指向有效索引)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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