将字符串输入到数组中

时间:2015-03-20 13:31:11

标签: java arrays string

我想从扫描仪输入收集的字符串,然后将它们放入String []我遇到的问题是我无法找到一种方法在几个语句中输入它们。我不想有任何循环,因为我不想让消息要求重复20次的名称。我想输入20个名字,每个名字之间有一个空格,进入数组中的20个不同的空格。

import java.util.Scanner;
public class Gradebook {
String[] lastName;
String[] firstName;
int[] ID;
int[][] testGrades;
int[][] hwGrades;
    public Gradebook(String[] lastName, String[] firstName, int[] ID, int[][] testGrades, int[][] hwGrades){
            Scanner input = new Scanner(System.in);
        this.lastName = new String[20];
        this.firstName = new String[20];
        this.ID = new int[20];
        this.testGrades = new int[20][5];
        this.hwGrades = new int[20][5];
            System.out.println("Enter last names of all people in alphbetical order: ");
            // this was my attempt to input them: 
         lastName[] = input.next();
    }

}

2 个答案:

答案 0 :(得分:0)

更好的方法是使用空格读取整个字符串,然后从空格中溢出,如下所示:

String input="asd asd";
String result[]=input.split("\\s+");

输出

output for specified input 'asd asd'
asd
asd

您的输入字符串将包含以空格分隔的单词。

答案 1 :(得分:0)

我不确定我是否清楚地理解了您的问题,但这里有一些代码:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] names = (in.nextLine()).split(" ");

 /* an input such as the following:
    this is an example

   would result in the following:
   names[] = {"this", "is", "an", "example"}; */
   }
}