【发布时间】:2019-05-27 03:48:16
【问题描述】:
请记住,我是初学者。 我编写了以下代码来尝试填充字符串数组。它运行但不会打印出字符串数组位置的内容。 (同样的事情似乎对双阵列没问题!)我不明白为什么会这样。如果有人可以帮助我解决这个问题,我将非常感激。请参阅下面的 Main Class 的代码和一个名为 Fruit 的类,其中包含我正在使用的方法。
`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;
}
}
【问题讨论】:
标签: java arrays string for-loop populate