Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用空格键拆分字符串_Java_Split_Spaces - Fatal编程技术网

Java 用空格键拆分字符串

Java 用空格键拆分字符串,java,split,spaces,Java,Split,Spaces,下面是我的java代码 我想输入:asd 123456 hellohello 输出: 自闭症 123456 你好 然而结果却是错误的。有人能帮我吗 包装试验 import java.util.Scanner; public class test1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner (

下面是我的java代码

我想输入:asd 123456 hellohello

输出:

自闭症

123456

你好

然而结果却是错误的。有人能帮我吗

包装试验

import java.util.Scanner;
public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner (System.in);
        String cs = sc.next();

        String[] output = cs.split("\\s+");
        System.out.println(output[0]);
        System.out.println(output[1]);
        System.out.println(output[2]);
    }
}
next()
只返回输入中的下一个标记,而不是整行,您的代码将抛出
ArrayIndexOutOfBoundsException
按原样bcoz
输出
的长度等于1


您需要
nextLine()
方法来获取整行内容。

我已经用您的代码解决了一些问题:

import java.util.Scanner;
public class SplitStringWithSpace {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String cs = sc.nextLine();
        //close the open resource for memory efficiency
        sc.close();
        System.out.println(cs);

        String[] output = cs.split("\\s+");
        for (String retval : output) {
            System.out.println(retval);
        }
    }
}
  • 使用增强的for循环,这样就不必手动导航阵列
  • 使用完资源后关闭它
此处
sc.next()
使用
空格
分隔符。因此,如果输入为
foo bar
,您将得到:

sc.next(); //`foo`
sc.next(); //`bar`
您可以选择
sc.nextLint()
并按原样使用其余代码。如果必须继续使用
sc.next()
,可以尝试此代码段

while(sc.hasNext()) { //run until user press enter key
  System.out.println(sc.next());
}

替换
sc.next()带有
sc.nextLine()我学到了一个新东西谢谢谢谢谢谢你我唯一的问题是:)@TLam非常欢迎你!如果答案对你有帮助,那么请投票/选择正确答案:)谢谢,我回答这个问题>~