-1

Ive been writing a program that is able to calculate a person's grades, but Im unable to turn a string into an String array (it says the array length is 1 when i put in 3 words). Below is my code. Where am I going wrong??

    protected static String[] getParts(){
    Scanner keyboard = new Scanner(System.in);

    System.out.println( "What assignments make up your overall grade? (Homework, quizzes, etc)" );
    String parts = keyboard.next();     

    Pattern pattern = Pattern.compile(" ");
    String[] assignments = pattern.split(parts);

    // to check the length

    for ( int i = 0; i < assignments.length; i++ )
        System.out.println(assignments[i]);

    return assignments;

}
  • see https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – kai May 14 '20 at 22:21
  • 2
    Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – kai May 14 '20 at 22:22

2 Answers2

3

Scanner::nextLine

Scanner::next() only consumes one word (it stops at whitespace). You want Scanner::nextLine, which consumes everything until the next line, and will pick up all your words.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
user
  • 7,435
  • 3
  • 14
  • 44
0

Use keyboard.nextLine instead:

    static String[] getParts()
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("What assignments make up your overall grade? (Homework, quizzes, etc)");
        String[] assignments = keyboard.nextLine().split(" ");

        for (String i : assignments)
            System.out.println(i);

        return assignments;
    }

NOTE: You also do not need to define a Pattern. You also do not need to return anything since the method already prints the strings. Unless of course you plan on using the values elsewhere