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)