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

时间:2021-11-27 21:44:39

The following program only works for 1 word or a number. If my input is more than 1 word, then after the 'space', the output leaves out the rest of the input. So, i want the print statement in the for-loop to print out the whole input as a String type including the spaces. Any suggestions?

以下程序仅适用于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 个解决方案

#1


0  

Replace the line

更换线

String svar = input.next();

String svar = input.next();

with

String svar = input.nextLine();

String svar = input.nextLine();

#2


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);
    }
  }
}

#3


0  

Credit goes to kai, this is the right code that worked for me. thanks! :)

归功于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] + " ");
        }
    }
}

#1


0  

Replace the line

更换线

String svar = input.next();

String svar = input.next();

with

String svar = input.nextLine();

String svar = input.nextLine();

#2


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);
    }
  }
}

#3


0  

Credit goes to kai, this is the right code that worked for me. thanks! :)

归功于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] + " ");
        }
    }
}