Please bear in mind that I am a beginner. I have written the following code to try to populate a String array. It runs but will not print out the contents of the String array positions. (The same thing seems to work no problem for the double Array!)I do not understand why this is. If anyone could help me solve this problem I would be extremely grateful. See below for the code of the Main Class and a class called Fruit which contains the methods I am using.
`enter code here`Main class:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in your shopping list:");
int listSize = scanner.nextInt();
String[] sl = new String[listSize];
double[] price = new double[listSize];
//Loop asking user to enter items and prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println("Enter item " + (i+1) + ":");
fruit.setName(scanner.nextLine());
sl[i] = fruit.getName();
scanner.next();
System.out.print("Price of " + sl[i] + ":");
fruit.setPrice(scanner.nextDouble());
price[i] = fruit.getPrice();
}
//Loop printing items and their prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println(sl[i] + " cost " + price[i]);
}
//Order the array in ascending order so as to be able to easily
identify the most and least expensive
Arrays.sort(price);
//Print out the most expensive and cheapest prices
System.out.println("The most expensive item costs: " +
price[price.length-1]);
System.out.println("The least expensive item costs: " + price[0]);
}
}
Fruit Class:
public class Fruit {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}