当前位置: 首页 > 知识库问答 >
问题:

我试图在用户输入的字符串中找到一个空格,但当我使用indexof(“”)时,它会返回-1作为值,我该如何解决这个问题?

汪典
2023-03-14

系统出来println(“请输入您的名字和姓氏,用空格隔开:”);试试(Scanner scan=new Scanner(System.in)){String s1=scan.next();

            int space = s1.indexOf(" ");
        
                String First_Name = s1.substring(0,space);
                String init1 = First_Name.substring(0,1);
                String Last_Name = s1.substring(space+1,s1.length());
                String init2 = Last_Name.substring(0,1);
        
        
                    int First_N = First_Name.length();
                    int Last_N = Last_Name.length();
        
                        System.out.println("You entered the name "+s1+".");
                        System.out.println("Your first name "+First_Name+": has "+First_N+" characters.");
                        System.out.println("Your last name "+Last_Name+": has "+Last_N+" characters.");
                        System.out.println("Your initials are "+init1+init2+".");

共有1个答案

隆扬
2023-03-14

你应该使用

String s1 = scan.nextLine();

而不是

String s1 = scan.next(); 
 类似资料: