【问题标题】:Inputting strings into an array将字符串输入到数组中
【发布时间】:2015-05-23 22:24:16
【问题描述】:

我想从扫描仪输入收集到的字符串,然后将它们放入 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();
    }

}

【问题讨论】:

    标签: java arrays string


    【解决方案1】:

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

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

    输出:

    output for specified input 'asd asd'
    asd
    asd
    

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

    【讨论】:

    • 更好的方法是使用 StringBuilder
    • @EvanBechtol,我不确定为什么在这种特殊情况下会很重要,但我 +1 了您的评论,因为我同意默认使用 StringBuilder 是一个很好的习惯。如果你发现自己试图用 String 做最琐碎的事情,那么 StringBuilder 就是你的人选。而且这是一种比 StringBuffer 更简洁的方法。
    【解决方案2】:

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

    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"}; */
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      相关资源
      最近更新 更多