0

私は C# を学び始めていますが、現時点では、変数が期待どおりに更新されていません。

string  Carpet,
        tempCarpet;  
Double  carpetPrice;

do{
Console.WriteLine("What type of carpet do you want: ");
Console.Write("1. Berber ($3.75) | 2. Plush ($4.62) | 3. Barbed ($9.98)");
tempCarpet = Console.ReadLine();
if (tempCarpet == "1") {
    Carpet = "Berber";
    carpetPrice = 3.75;
} else if (tempCarpet == "2") {
    Carpet = "Plush";
    carpetPrice = 4.62;
} else if (tempCarpet == "3") {
    Carpet = "Barbed";
    carpetPrice = 9.98;
} else
    Console.WriteLine("Invalid Selection.");
}while(tempCarpet != "1"|tempCarpet != "2"|tempCarpet !="3"); 

Console.WriteLine("The Carpet" + Carpet + "costs {0:C}", carpetPrice);

` Use of unassigned local variable というエラーが表示されます。人が望む「カーペット」を選択するオプションが欲しいので、私はそれをこの種の形式にしたいと考えています。この問題の解決策を知っている人はいますか?

4

7 に答える 7

2

You are initializing Carpet inside the condition and compiler can't determine whether the code will reach there. You may do

string Carpet = null;

Or you can assign it some default value in the last part of else.

Same is the case with carpetPrice.

于 2013-03-05T08:49:08.390 に答える
1

変化する

Double = carpetPrice;

Double carpetPrice;
于 2013-03-05T08:48:51.223 に答える
0

間違った状態があります:

            }while(tempCarpet != "1"|tempCarpet != "2"|tempCarpet !="3");

への変更:

            } while (tempCarpet != "1" && tempCarpet != "2" && tempCarpet != "3");

しかし、より良い方法は次のとおりです。

string Carpet = null;
// ...
// There is some code
// ...
} while (null == Carpet);
于 2013-03-05T09:18:06.487 に答える
0

これにはスイッチを使用した方がよいでしょう。

  switch(tempCarpet){ 

case "1" : Carpet = "Berber";
            carpetPrice = 3.75;
    break;

case "2" : Carpet = "Plush";
            carpetPrice = 4.62;
    break;

case "3" : Carpet = "Barbed";
            carpetPrice = 9.98;
    break;
default : Console.WriteLine("Invalid Selection.");
    break;

}
于 2013-03-05T08:54:43.807 に答える
0

You are declaring variables the wrong way :

string = Carpet,
         tempCarpet;  
Double = carpetPrice;

Correcr format of declaration is : datatype var_name [ = value]

Correcy way would be :

string Carpet = null, tempCarpet = null;
double carpetPrice = 0;
于 2013-03-05T08:50:07.950 に答える
0

This is not compilable code;

At the top:

string = Carpet,
                     tempCarpet;  
            Double = carpetPrice;

This should look something like

string carpet= "";
string tempCarpet = "";
double carpetPrice;

It would perhaps clear things up to assign the strings an initial value, to ensure that they are set before usage. The double is a different matter as it's a value type. Strings are reference types.

于 2013-03-05T08:50:12.013 に答える
0

これはコンパイラ エラーです

string = Carpet,
                         tempCarpet;  
                Double = carpetPrice;

修正コード:-

string Carpet = tempCarpet;
 Double = carpetPrice = 1020.00;
于 2013-03-05T08:50:30.573 に答える