当我运行代码时,最终输出是公寓#204的租金为$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);
}
答案 0 :(得分: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);
}
有效吗?
答案 1 :(得分: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语句之外。
优良作法是将括号用于单个语句:
此外,printit
函数将rent
作为一个数组,它应该只是一个int(虽然你应该在这里使用浮点类型):
static void printit (int apartmentNumber, int rent)
{
....
}
然后方法的主体才有意义。
然后对它的调用变为:
printit(apartmentNumber, rent[i]);
因为它将在循环中。