Skip to Main Content

Unable to create string array

supertoyMar 24 2018 — edited Mar 24 2018

I'm still pretty new to Java so arrays still have me troubled.

What I'm trying to do: Have the user input an unknown number of string entries and then print out the array. This is part of a larger task where I will loop over each entry and perform a task. But for now I'm just trying to get the array working.

What is expected: User enters Apple Banana Lemon and the output shows:

Apple

Banana

Lemon

What is happening is:User enters Apple Banana Lemon and the output shows:

Apple Banana Lemon

When I hard code the array my array prints correctly (What is expected) when I input the values using Scanner I get the other results (What is happening).

This produces the desired output:

import java.lang.String;

public class fruit {

   public static void main(String[] args) {

  String fruits[] = {"apple", "banana", "lemon"};

   for (int i = 0; i < fruits.length; i++)

  {

  System.out.println(fruits[i]);

  }

  }

}

apple

banana

lemon

Process finished with exit code 0

This produces the incorrect output:

import java.util.*;

import java.lang.String;

public class fruits {

   public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);

  System.out.println("Enter some fruit: ");

  String name = sc.nextLine();

  String fruits[] = {name};

   for (int i = 0; i < fruits.length; i++)

  {

  System.out.println(fruits[i]);

  }

  }

}

Enter some fruit:

apple banana lemon

apple banana lemon

Process finished with exit code 0

Built with JetBrains IntelliJ

java version "1.8.0_161"

Java(TM) SE Runtime Environment (build 1.8.0_161-b12)

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on Apr 21 2018
Added on Mar 24 2018
2 comments
289 views