2016-06-04 2 views
0

У меня возникли проблемы с моим кодом возвращающей -1, если isPicked находится в моем GetWoodTypes метода False, мой если заявление полностью игнорируется, и я не могу найти проблему в коде , если кто-то может помочь, что было бы здоровоVb.net Метод не возвращает значение

Public Class Class1 

    Shared Sub Main() 
     Dim woodType() As String = {"Pine", "Oak", "Elm"} 
     Dim woodPrice() As Integer = {100, 140, 200} 
     Dim nameIndex As Integer = 0 
     nameIndex = GetWoodTypes(woodType, woodPrice) 
     Dim Quantity As Integer = 0 
     Dim basePrice As Integer = 0 
     Quantity = GetDrawerQtys() 
     basePrice = GetPrices(woodType, woodPrice, nameIndex, Quantity) 


     If nameIndex = -1 Then 
      Console.Write("You have made the wrong selection, Please try Again") 
      Console.ReadLine() 
     Else 
      DisplayResults(Quantity, woodType, woodPrice, basePrice, nameIndex) 
     End If 
    End Sub 

    Public Shared Function GetWoodTypes(values() As String, Price() As Integer) 
     Console.Write("Please select the type of wood you would like to purchase: Pine,Oak,Elm ") 
     Dim Selectedwood As String = Console.ReadLine() 
     Dim ispicked As Boolean = False 
     Dim location As Integer = 0 
     For i As Integer = 0 To values.Count - 1 
      If Selectedwood.ToLower = values(i).ToLower Then 
       ispicked = True 
       location = i 
      End If 
     Next i 
     If ispicked Then 
      Console.WriteLine("Thank you for selection, you have picked {0} at {1} ", values(location), Price(location)) 
      Return location 
     Else 
      Console.Write("Sorry") 
      Return -1 
     End If 
    End Function 

    Public Shared Function GetDrawerQtys() 
     Console.WriteLine(" How Many Drawers do you want ") 
     Dim DrawerQty As Integer = Console.ReadLine() 
     Return DrawerQty 
    End Function 

    Public Shared Function GetPrices(types() As String, price() As Integer, location As Integer, Quantity As Integer) 
     Console.Write("You have ordered a {0} with {1} drawers at {2} each ", types(location), Quantity, price(location)) 
     Dim Amount As Integer = (Quantity * 30) + price(location) 
     Return Amount 
    End Function 

    Public Shared Sub DisplayResults(Quantity As Integer, type() As String, price() As Integer, basePrice As Integer, location As Integer) 

     Console.WriteLine("Hello you have purchased {0} {1} at {2} your total is {3} ", Quantity, type(location), price(location), basePrice) 
     Console.ReadLine() 
    End Sub 
End Class 
+0

У вас есть 2 хороших ответа. Если один из них ответил на ваш вопрос, правильная вещь - щелкнуть галочку. [Тур] – user3697824

ответ

0

Вы не проверяли nameIndex сразу после вызова GetWoodTypes. Это приведет вас к дальнейшему, но до сих пор проблема с GetDrawerQtys, если вы не вводите целое число.

Shared Sub Main() 

     Dim woodType() As String = {"Pine", "Oak", "Elm"} 
     Dim woodPrice() As Integer = {100, 140, 200} 
     Dim nameIndex As Integer = 0 
     nameIndex = -1 
     Dim Quantity As Integer = 0 
     Dim basePrice As Integer = 0 
     'Quantity = GetDrawerQtys() 
     'basePrice = GetPrices(woodType, woodPrice, nameIndex, Quantity) 

     nameIndex = GetWoodTypes(woodType, woodPrice) 
     While nameIndex = -1 
      Console.WriteLine("You have made the wrong selection, Please try Again") 
      nameIndex = GetWoodTypes(woodType, woodPrice) 
     End While 

     Quantity = GetDrawerQtys() 
     basePrice = GetPrices(woodType, woodPrice, nameIndex, Quantity) 
     DisplayResults(Quantity, woodType, woodPrice, basePrice, nameIndex)  
    End Sub 


    Public Function GetDrawerQtys() 

     Dim validQty As Boolean = False 
     Dim DrawerQty As Integer 

     While Not validQty 
      Console.WriteLine(" How Many Drawers do you want ") 
      validQty = Int32.TryParse(Console.ReadLine(), DrawerQty) 
     End While 

     Return DrawerQty 

    End Function 
1

Я бы подошел к этому по-другому.

Во-первых, я хотел бы определить отдельный класс для хранения типа и цена конкретного дерева:

Public Class Wood 
    Public Property Type As String 
    Public Property Price As Integer 
End Class 

Тогда я бы создать отдельный класс для ведения дерева и выбор количества, расчета цены и показывая результат заказа.

Примечание: тип декларации функции должен быть также декларирован для ясности, например.
Public Function GetSomeNumber() As Integer

Также я использовал .Select() и .FirstOrDefault() методы. Они входят в состав LINQ. Они принимают параметр lambda expression. На всякий случай вы еще не встретились с ними.

Public Class Shop 

    Dim woods As List(Of Wood) 

    Public Sub New() 

     ' Initialize the "product catalogue" using collection initializer combined with object initializer. 
     woods = New List(Of Wood) From 
     { 
      New Wood() With {.Type = "Pine", .Price = 100}, 
      New Wood() With {.Type = "Oak", .Price = 140}, 
      New Wood() With {.Type = "Elm", .Price = 200} 
     } 

    End Sub 

    Public Function SelectWood() As Wood 

     Dim selectedWood As Wood = Nothing 
     Dim woodTypes As String = String.Join("/", woods.Select(Function(wood) wood.Type).ToArray()) 

     While True 

      Console.Write("Please select the type of wood you would like to purchase [{0}]: ", woodTypes) 

      Dim selectedWoodType As String = Console.ReadLine() 

      ' Instead of ToLower() you may use String.Equals() so that you can specify if you want to compare ignoring case. 
      ' FirstOrDefault() means that if the user typed a wood type correctly then returns the correct Wood object; otherwise, Nothing. 
      selectedWood = woods.FirstOrDefault(Function(wood) String.Equals(wood.Type, selectedWoodType, StringComparison.OrdinalIgnoreCase)) 

      If (selectedWood IsNot Nothing) Then 
       Exit While 
      End If 

      Console.WriteLine("Sorry.") 

     End While 

     Console.WriteLine("Thank you for selection, you have picked {0} at {1}", selectedWood.Type, selectedWood.Price) 

     Return selectedWood 

    End Function 

    Public Function GetDrawerQtys() As Integer 

     Dim drawerQty As Integer 
     Dim rawQty As String = Nothing 

     Do 
      Console.Write("How many drawers do you want? ") 
      rawQty = Console.ReadLine() 
     Loop Until Int32.TryParse(rawQty, drawerQty) 

     Return drawerQty 

    End Function 

    Public Function CalculatePrice(wood As Wood, quantity As Integer) As Integer 
     Console.WriteLine("You have ordered a {0} with {1} drawers at {2} each.", wood.Type, quantity, wood.Price) 
     Return wood.Price + 30 * quantity 
    End Function 

    Public Sub DisplayOrder(wood As Wood, quantity As Integer, basePrice As Integer) 
     Console.WriteLine("Hello, you have purchased {0} {1} at {2} your total is {3}.", quantity, wood.Type, wood.Price, basePrice) 
     Console.ReadLine() 
    End Sub 

End Class 

Тогда у вас может быть модуль, в котором вы можете использовать эти классы.

Module Module1 

    Sub Main() 

     Dim shop As New Shop() 

     Dim selectedWood As Wood = shop.SelectWood() 
     Dim quantity As Integer = shop.GetDrawerQtys() 
     Dim basePrice As Integer = shop.CalculatePrice(selectedWood, quantity) 

     shop.DisplayOrder(selectedWood, quantity, basePrice) 

    End Sub 

End Module 
Смежные вопросы