如何在数组中打印单词,并在它们之间包含空格?

时间:2014-06-17 13:03:59

标签: java string for-loop input java.util.scanner

以下程序仅适用于1个字或数字。如果我的输入超过1个单词,那么在'空格'之后,输出将遗漏输入的其余部分。所以,我希望for循环中的print语句将整个输入打印为包含空格的String类型。有什么建议吗?

import java.util.*;

class characters {

    public static void main(String[] args) {

        int upperC = 0;
        int lowerC = 0;
        //char ch;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter input: ");
        String svar = input.next();

        String[] ary = svar.split("");

        for (int i=0; i< ary.length; i++) {
            System.out.print(ary[i]);
        }
    }
}

3 个答案:

答案 0 :(得分:0)

替换

String svar = input.next();

String svar = input.nextLine();

答案 1 :(得分:0)

import java.util.*;

   class characters {

public static void main(String[] args) {

    int upperC = 0;
    int lowerC = 0;
    //char ch;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter input: ");
    String word = input.nextLine();
    System.out.println("your complete String"+word);
    }
  }
}

答案 2 :(得分:0)

归功于kai,这是适合我的正确代码。谢谢! :)

import java.util.*;

class characters {

    public static void main(String[] args) {

        int upperC = 0;
        int lowerC = 0;
        char ch;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter input: ");
        String svar = input.nextLine();

        String[] ary = svar.split(" ");

        for (int i=0; i< ary.length; i++) {
            System.out.print(ary[i] + " ");
        }
    }
}