2013-11-21 11 views
0

所以我從自己購買的一本書教自己的Java,其中一個練習就是詢問用戶他們想要什麼樣的物品,並給他們輸入物品的價格。目前爲止,我設置了這個設置:如何在數組中找到用戶輸入的字符串並獲取位置而不使用if或select?

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

爲什麼你不能使用'if'或'select'? – nhgrif

回答

4

不使用,如果:

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); 
相關問題