如何读取字符串,然后将其保存到Java中的数组

时间:2019-05-25 15:52:44

标签: java

我想读取一个字符串,然后将其放在Java中字符串数组的第一个位置

enter code here


for (int i=1;i<100;i++) {

            System.out.print("Enter a string : ");

            Scanner scanner = new Scanner(System. in);

            String inputString = scanner.nextLine();
            System.out.println("String read from console is : \n"+inputString);
            inputString = thisIsAStringArray[];
}

2 个答案:

答案 0 :(得分:1)

读取字符串应该使用while循环完成,但是您想要做的事情在这里完成。此解决方案将字符串保存到仅第一个索引。

public static void main(String [] args) {
       String [] thisIsAStringArray = new String[20]; //Only 20 string can be saved.
       Scanner in = new Scanner(System.in);
      for(int i = 0; i < 100;i++) {
        thisIsAStringArray[0] = in.nextLine(); ///Save element to first position.
        System.out.println("String entered is " + thisIsAStringArray[0]); //Get the element from the first position.
       }

}

此解决方案不会保存到第一个位置,而是保存到数组的每个索引。

public static void main(String [] args) {
        String [] thisIsAStringArray = new String[20]; //Only 20 string can be saved.
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < thisIsAStringArray.length;i++) {
            thisIsAStringArray[i] = in.nextLine(); ///Save element to first position.
            System.out.println("String entered is " + thisIsAStringArray[i]); //Get the element from the first position.
        }

    }

答案 1 :(得分:0)

因此,您将创建一个字符串列表,并在字符串数组的开头分配该字符串。您还可以使用辅助函数获得数组头的索引。

String[] thisIsAStringArray = new String[10];
for (int i=1;1<100;i++) {

            System.out.print("Enter a string : ");

            Scanner scanner = new Scanner(System. in);

            String inputString = scanner.nextLine(); // READ IN THE STRING 
            System.out.println("String read from console is : \n"+inputString);
            int pos= firstNonullPosition(thisIsAStringArray);
            if(pos!=-1)
                thisIsAStringArray[]=inputString; 
            else
                System.out.println("Array is full!");
            System.out.println("The String at the position 0 of the String array thiIsAStringArray is:" +thisIsAStringArray[0]);


}

public static int firstNonullPosition(String[] a)
{
    int index=0;
    while(a[index]!= null)
    {  
         index++;
         if (index > a.length)
             return -1;
    }
    return index;

}