2017-02-03 23 views
0

私はホテルのマネージャーをあなた自身のクラスを使って作成しようとしています。あなたの部屋の高さに応じて費用を計算できます。オーシャンビュー、ベッドルーム数それらの3つの変数に応じて費用を吐き出す。c#ホテルの部屋/計算を管理するコードを書く

これを計算せずに実行しようとすると、これまでの動作を確認するだけで、入力したものを返すことはできないため、私は立ち往生しています。エラーが発生しました。「FormatExceptionが発生しました」と言われました。

私はC#にはかなり新しくなっています。 Console.WriteLineため

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

フォーマット文字列は6つのプレースホルダがあります。

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

をしかし、あなたは唯一の5引数を渡しています。引数をもう1つ追加するか、最後のプレースホルダを削除します。


あなたはアパートのクラスインスタンスの値を表示したい場合にも、それはそれは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,3ベッドルーム900 $があるかどうかに応じて変数を追加したいとします。これらの数値をベース価格として使用し、オーシャンビューで50ドル、アパート番号が300より大きい場合は25ドルを追加します。 通貨を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ドル、アパート番号が300より大きい場合は25ドルを追加します。0ドルから始まる通貨に使用する別の文字列を作成しますか?次に、1寝室に1を入れた場合と同様に、入力した数字と比較して800 $を追加しますか? –

関連する問題