簡體   English   中英

為什么我的println不起作用?

[英]Why isn't my println working?

該程序沒有打印出感謝(姓名)。 取而代之的是,該行被完全跳過,循環回到主菜單。 有人可以解釋為什么嗎? 它應該根據指示的索引創建一個新字符串,並將結果存儲在“ 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) {
        }
    }
}

您的代碼在下面的行上生成IndexOutOfBoundsException ,並跳轉到Exception處理程序代碼。

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

String.substring重載,並且具有兩個定義:

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

在Java中, char數據類型只是幕后的16位數字。 它將' ' (空格)轉換為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