所以我从我买的一本书中自学Java,其中一个练习就是询问用户他们想要什么样的项目并给他们输入的项目的价格。到目前为止我已经设置了这个:
String[] flowerName = {"Pentunia", "Pansy", "Rose", "Violet", "Carnation"};
String[] flowerPrice = {".50", ".75", "1.50", ".50", ".80"};
System.out.println("What kind of flower would you like?");
Scanner keyboard = new Scanner(System.in);
String strFlowerIn = keyboard.next();
System.out.println("How many would you like?");
String strFlowerNumIn = keyboard.next();
因此,如果用户输入玫瑰,它会询问结果有多少:
3 Roses = 1.50 * 3 = 4.50
如何获取他们输入的内容并将其与数组进行比较以找到索引?
答案 0 :(得分:4)
不使用if:
int index = Arrays.asList(flowerName).indexOf(strFlowerIn);
double price = flowerPrice[index];
double total = price * intFlowerNumIn;
您必须在代码中更改一些内容。这是一个完整的例子:
String[] flowerName = {"Pentunia", "Pansy", "Rose", "Violet", "Carnation"};
Double[] flowerPrice = {.50d, .75d, 1.50d, .50d, .80d};
System.out.println("What kind of flower would you like?");
Scanner keyboard = new Scanner(System.in);
String strFlowerIn = keyboard.nextLine();
int index = Arrays.asList(flowerName).indexOf(strFlowerIn);
System.out.println("How many would you like?");
int intFlowerNumIn = keyboard.nextInt();
decimal price = flowerPrice[index];
decimal total = price * intFlowerNumIn;
System.out.println("Total price: " + total);