2017-02-03 98 views
0

因此,我試圖讓一個酒店經理使用它自己的類來計算成本,具體取決於房間的高度,海景,多少間臥室和它根據這3個變量吐出成本。c#編寫一個管理酒店房間的代碼/計算

我被卡住了,因爲當我嘗試運行這個沒有任何計算,只是爲了看看它是否工作到目前爲止它不會返回/重申我已經輸入。有一個錯誤說「FormatException發生」

我對c#很新,所以我很感激任何可以給予的幫助。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace myHotel 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     Apartment myApartment = new Apartment(); 
     Console.WriteLine("Hotel Building Number:"); 
     myApartment.BuildingNumber = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("Please enter your Hotel room number:"); 
     myApartment.ApartmentNumber = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("Please enter the number of Bedrooms you have:"); 
     myApartment.Type = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("Please enter 1 for Ocean View and 2 for no Ocean view:"); 
     myApartment.View = Convert.ToInt32(Console.ReadLine()); 
     Console.WriteLine("Please enter your name"); 
     myApartment.Name = Console.ReadLine(); 

     Console.WriteLine("{0} {1} {2} {3} {4} {5}", 
      myApartment.BuildingNumber, 
      myApartment.ApartmentNumber, 
      myApartment.Type, 
      myApartment.View, 
      myApartment.View); 

     Console.ReadLine(); 
    } 

} 
class Apartment 
{ 
    public int BuildingNumber { get; set; } 
    public int ApartmentNumber { get; set; } 
    public int Type { get; set; } 
    public int View { get; set; } 
    public string Name { get; set; } 

} 

} 

回答

5

Console.WriteLine格式字符串有6個佔位符:

"{0} {1} {2} {3} {4} {5}" 

但您只通過5個參數。要麼添加一個參數,要麼刪除最後一個佔位符。


此外,如果你想顯示從公寓類實例的值,它可能是有意義的覆蓋它的ToString()方法。例如: -

class Apartment 
{ 
    public int BuildingNumber { get; set; } 
    public int ApartmentNumber { get; set; } 
    public int Type { get; set; } 
    public int View { get; set; } 
    public string Name { get; set; } 

    public override string ToString() 
    { 
     return $"{BuildingNumber} {ApartmentNumber} {Type} {View} {Name}"; 
    } 
} 

現在顯示這將是簡單的:

Console.WriteLine(myApartment); 
+0

謝謝,我接受了你的建議,它的工作很棒。 現在,如果我想添加變量,取決於房間是否有1臥室800 $,2臥室850,3bedrooms 900 $。使用這些數字作爲基準價格,然後增加50美元的海景,然後25美元,如果你的公寓數量高於300. 我會使用另一個字符串致力於貨幣從0 $開始? –

0

你的格式字符串有更多的插值點比你有參數。嘗試:

Console.WriteLine("{0} {1} {2} {3} {4}", 
     myApartment.BuildingNumber, 
     myApartment.ApartmentNumber, 
     myApartment.Type, 
     myApartment.View, 
     myApartment.View); 
+0

謝謝,我解決了它,它的工作原理!現在如果我想添加變量,取決於房間是否有1間臥室800 $,2臥室850,3牀房900 $。使用這些數字作爲基準價格,然後增加50美元的海景,然後25美元,如果你的公寓號碼高於300.我會做另一個字符串專用於貨幣從0 $開始?然後比較他們輸入的數字,比如他們爲1個臥室添加1,添加800 $? –