0

当我运行代码时,最终输出是 Rent for apartment # 204 is $System.Int32[]。我的问题的重点是getRent方法。当我进入代码时,for 循环函数会找到用户输入apartmentNumber,然后运行单元数组以匹配索引。所以当它进入printit方法时,它仍然显示用户输入apartmentNumber

如何匹配相应的租金指数?

static void Main(string[] args)
{
    int[] apartment = { 123, 204, 601, 609, 612 }; // initialize apartment array
    int[] rent = {500, 750, 495, 800, 940 }; // intitialize rent array
    int apartmentNumber = 0; // declare apartmentNumber int

    getRent (apartment , rent, apartmentNumber ); /*pass the apartment and rent 
    array by ref and apartment number console entry */

    Console.WriteLine("Press any key to continue..."); // Lets user know program over
    Console.ReadKey(); // keeps the program from closing quickly after executing
}

static void getRent(int [] apartment, int [] rent, int apartmentNumber) //method getRent
{ 
    Console.WriteLine ("Enter apartment number"); // query user to enter apartment number
    apartmentNumber = int.Parse (Console.ReadLine ()); // convert apartment number to int

    for (int i = 0; i < apartment.Length - 1; i++) // for loop to match apartmentNumber

    if (apartment[i] == apartmentNumber)// match it to apartment array


    Console.WriteLine(); // space between user input and output
    printit(apartmentNumber, rent);
}

static void printit (int apartmentNumber, int [] rent) // static method printit 
{
    string string1 = "Rent for apartment #" + apartmentNumber;
    string string2 = " is $" + rent;

    StringBuilder mystring = new StringBuilder();

    mystring.Append(string1);
    mystring.Append(string2);
    Console.WriteLine(mystring); 
}
4

2 回答 2

0

本质上,您的getRent方法所做的只是将调用转发给printit方法。请注意,printit调用getRent既不是if代码块的一部分,也不是for代码块的一部分。

此外,您希望string2在方法变量中存储printit什么?您将 + 运算符与字符串和数组一起使用。如果这是 C#,则rent数组的字符串表示将连接到“is $”。

编辑:这就是您需要的:以下语句中的指令块:

if (apartment[i] == apartmentNumber)// match it to apartment array

应该如下:

{
    int apartmentRent = rent[i];
    System.out.println("Rent for apartment # " + apartmentNumber + "is $ " + apartmentRent);
}

它有效吗?

于 2013-11-10T22:06:28.053 回答
0

您没有为for循环和if语句使用括号。

所以这段代码:

for (int i = 0; i < apartment.Length - 1; i++) // for loop to match apartmentNumber

if (apartment[i] == apartmentNumber)// match it to apartment array

Console.WriteLine(); // space between user input and output
printit(apartmentNumber, rent);

实际上是这样做的:

for (int i = 0; i < apartment.Length - 1; i++) // for loop to match apartmentNumber
{
    if (apartment[i] == apartmentNumber)// match it to apartment array
    {
        Console.WriteLine(); // space between user input and output
    }
}
printit(apartmentNumber, rent);

所以你可以看到调用printit在循环和 if 语句之外。

即使对于单个语句,使用括号也是一种很好的做法:

  1. 这样更容易发现此类问题。
  2. 它可以更轻松地将代码添加到循环中的正确位置,以及以后需要的 if 语句。

当你的函数可能只是一个 int 时,你的printit函数也被rent当作一个数组(尽管你应该在这里使用浮点类型):

static void printit (int apartmentNumber, int rent)
{
     ....
}

那么方法的主体是有意义的。

然后对它的调用变为:

printit(apartmentNumber, rent[i]);

因为那将在循环内。

于 2013-11-10T22:07:41.787 回答