简体   繁体   中英

Convert string user input to array

Ok so I'm trying to create a programmed where the user is asked to enter a word, this word is then stored as a variable, and then its displayed as an array.

This is what I have so far:

package coffeearray;

    import java.util.Arrays;
    import java.util.Scanner;
    import java.lang.String;
    import java.util.ArrayList;

    public class Main {


    public static void main(String[] args) {

        String drink;
        String  coffee;


        int [] a =new int[6];

        Scanner in = new Scanner(System.in);
        System.out.println("Please input the word coffee");
        drink = in.next();

So basically I need some code so that the word stored is then displayed as variable. For example "Coffee" would then be displayed but each letter on its own line.

I've searched all over and can't seem to find out how to do this. Thanks in advance.

Given string str :

String str = "someString"; //this is the input from user trough scanner
char[] charArray = str.toCharArray();

Just iterate trough character array. I'm not going to show you this as this can easily be googled. Again if you're really stuck let me know, but you should really know this.

Update Since you're new to Java. Here is the code per Jeff Hawthorne comment :

(for int i=0, i < charArray.getlength(); i++){
   System.out.println(charArray[i]);
}

You can use String.split("")

Try this:

String word = "coffee"; //you get this from your scanner
if(word.length()>0)
   String [] characterArray = Arrays.copyOfRange(word.split(""), 1, word.length()+1);

You can convert the String to a CharSequence:

CharSequence chars = inputString.subSequence(0, inputString.length()-1);  

you can then iterate over the sequence, or get individual characters using the charAt() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM