2015-11-13 91 views
-1
using System; using System.Collections.Generic; using System.Linq; 
using System.Text; using System.Threading.Tasks; 

namespace Assignment12 { 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      bool found; 
      string[] toppings = { "cheese", "pepperoni", "green pepper", "onion", "mushroom" }; 
      double[] price = { 1.30, 1.90, 1.80, 1.70, 1.60 }; 

      Console.WriteLine("Choose a topping: cheese, pepperoni, green pepper, onion or mushroom"); 
      Console.WriteLine("Please type the topping that you want - exactly as it appears above:"); 
      string order = Console.ReadLine(); 
      Console.WriteLine("\nYou chose: " + order); 

      found = false; 
      for (int i = 0; i < 5; i++) 
      { 
       if (order.Equals(toppings[i])) 
       { 
        found = true; 
       } 
      } 
      if (!found) 
      { 
       Console.WriteLine("The product " + order + " was not found, please try again!!!!!!\n"); 
       Console.WriteLine("Hit any key to close"); Console.ReadKey(true); 
       return; 
      } 
// The problem is here with the local variable "price" 
      Console.WriteLine("The price of " + order + " is $" + price); 
// I also tried 1.30, 1.90, 1.80, 1.70, 1.60 but still not working 
      Console.WriteLine("Hit any key to close"); Console.ReadKey(true); 
     } 
    } 
} 

回答

-1

當你搜索你的餡料,你需要記住的價格:

found = false; 
double priceFound = 0; 
for (int i = 0; i < 5; i++) 
{ 
    if (order.Equals(toppings[i])) 
    { 
     found = true; 
     priceFound = price[i]; // store the found price 
    } 
} 

Console.WriteLine("The price of " + order + " is $" + priceFound); 

但是,你並不需要通過自己的數組中進行迭代。
這一切都可以使用Array.IndexOf更容易完成。此方法返回數組中項目的索引,如果尚未找到項目,則返回-1

static void Main(string[] args) 
{ 
    string[] toppings = { "cheese", "pepperoni", "green pepper", "onion", "mushroom" }; 
    double[] price = { 1.30, 1.90, 1.80, 1.70, 1.60 }; 

    Console.WriteLine("Choose a topping: cheese, pepperoni, green pepper, onion or mushroom"); 
    Console.WriteLine("Please type the topping that you want - exactly as it appears above:"); 
    string order = Console.ReadLine(); 
    Console.WriteLine("\nYou chose: " + order); 

    int index = topping.IndexOf(order); 

    if (index == -1) 
    { 
     Console.WriteLine("The product " + order + " was not found, please try again!!!!!!\n"); 
     Console.WriteLine("Hit any key to close"); Console.ReadKey(true); 
     return; 
    } 

    Console.WriteLine("The price of " + order + " is $" + price[index]); 
    Console.WriteLine("Hit any key to close"); 
    Console.ReadKey(true); 
}  
+0

@AnassElbekkari你是什麼意思的「不工作」?它顯示編譯錯誤,引發運行時異常還是給出錯誤的結果? –

+0

謝謝。它現在有效。我使用了第一種解決方案。 – AnsBekk