首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的println不能工作?

问为什么我的println不能工作?
EN

Stack Overflow用户
提问于 2017-02-22 05:12:57
回答 2查看 82关注 0票数 1

程序没有打印出感谢(名字)。相反,该行被完全跳过,循环回到主菜单。有人能解释一下为什么吗?它应该根据指定的索引创建一个新字符串,并将结果存储在'firstName‘中,然后将其打印为“谢谢(名称)!”

代码语言:javascript
复制
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) {
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-22 05:22:24

您的代码将在下面的行上生成一个IndexOutOfBoundsException,并跳转到异常处理程序代码。

代码语言:javascript
复制
String firstName=custInfo[counter].substring(0,(' '));

String.substring是重载的,它有两个定义:

代码语言:javascript
复制
substring(int startIndex)
substring(int startIndex, int endIndex)

在Java语言中,char数据类型只是幕后的16位数字。它正在将' ' (空格)转换为32,并且将在任何长度小于32的字符串上出错(假定计数器指向有效的索引)

票数 4
EN

Stack Overflow用户

发布于 2017-02-22 05:24:54

使用下面的代码来获取name和DoB之间空格的索引:

代码语言:javascript
复制
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42378086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档