我正在参加编程课程,我遇到了一项任务问题。代码应该计算一个值,但我总是得到的答案是0.不确定我做错了什么但希望有人可以帮助我并向我解释我的错误在哪里? 有关初学者的提示吗?
class changeValue
{
//Create a class called changeValue that declares 2 integer class variables: value1 and
// value2. These should be declared as public and you should not use automatic properties
// to declare them.
private int _value1;
private int _value2;
public int Value1
{
get
{
return _value1;
}//end get
set
{
_value1 = value;
}//end set
}
public int Value2
{
get
{
return _value2;
}//end get
set
{
_value2 = value;
}//end set
}
public changeValue(int val1, int val2)
{
//here is the constructor where you code the if statements
int value1 = val1;
int value2 = val2;
if (value1 > 5)
{
value1 = val1;
}
if (val1 <= 5)
{
value1 = (val1+val2);
}
if (val2 < 10)
{
value2 = (val2 * val2 + 5);
}
if (val2 >= 10)
{
value2 = val2;
}
}
public void printit()
{
//here is the printit method used to print the results
Console.WriteLine("The calculated value is:" + (Value1 * Value2));
}
}
class assignment3
{
public static void Main(string[] args)
{
//declare the local val1 and val2 integer variables
int val1;
int val2;
//prompt the user for input of two integers
//don’t forget to convert from the string input to integer
Console.Write("Enter an integer value: "); //obtain user input
val1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter a second integer value: "); //obtain user input
val2 = Convert.ToInt32(Console.ReadLine());
//instantiate a changeValue object here
changeValue myValue = new changeValue(val1,val2);
myValue.printit();//call the object method printit here
}
}
}
感谢所有帮助,这个课程并不容易。
答案 0 :(得分:2)
在你的changeValue方法中,你要定义不使用你的字段的局部变量
int value1 = val1;
int value2 = val2;
=&GT;
_value1 = val1;
_value2 = val2;
答案 1 :(得分:0)
在changeValue中,您有局部变量value1和value2。您的类有变量_value1和_value2。显然,这些名字是不同的。您想要更改局部变量还是类变量?
我应该补充说你正在做C#属性,所以你也有属性Value1和Value2,它们也不同于你的本地变量value1和value2(因为大写字母V)