当程序运行时,它会要求您输入产品名称和价格,然后每当您按 -1 时,它就会停止并显示输入的产品和价格的列表。但是,问题是我编写了一个选择排序算法,以按 PRICE 升序对列表进行排序。输出不是我所期望的。看看这段代码中的“//选择排序”
import java.util.Scanner;
public class ProductPrices {
private static Scanner keyboard = new Scanner(System.in);
private static Scanner key = new Scanner(System.in);
final static int arrayLength = 1000; //maximum array size
static float[] productPrice = new float[arrayLength]; //stores the prices of products
static String[] productName = new String[arrayLength]; //stores the names of products
public static void main(String[] args) {
System.out.println("SHOPPING. Press -1 to quit anytime.\n");
for(int i=0; i<arrayLength; i++) {
System.out.print("Product: ");
productName[i] = keyboard.nextLine();
if(productName[i].equals("-1"))
break;
System.out.print("Price: $");
productPrice[i] = key.nextFloat();
if(productPrice[i] < 0)
break;
}
System.out.println("\nList of the SHOPPING!\n---------------------");
for(int i=0; i<productPrice.length; i++) {
if(productName[i] == null || productName[i].equals("-1") || productPrice[i] < 0)
continue; // null arrays will not be displayed.
else {
// Selection sort
if(productPrice[i] > productPrice[i+1]) {
float temp = productPrice[i];
productPrice[i] = productPrice[i+1];
productPrice[i+1] = temp;
}
System.out.printf("Item: %s %.2f\n", productName[i], productPrice[i]);
}
}
}
}
For example :::Input::: Product: apple Price: $2.35 Product: pie Price: $1.36 Product: cereal Price: $7.4 Product: -1 :::Output::: Item: apple 1.36 Item: pie 2.35 Item: cereal 0.00 That is incorrect, it should be Item: pie 1.36 Item: apple 2.35 Item: cereal 7.40