计算值始终为0,我不知道为什么
我正在接受编程课的介绍,并且遇到了作业问题。该代码应该计算一个值,但我总是得到的答案是0.不知道我做错了什么,但希望有人能帮助我,并向我解释我的错误在哪里? 初学者的任何提示?计算值始终为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
}
}
}
感谢所有这种帮助,这个类是不容易的。
在你changeValue方法你定义了不使用你的领域
int value1 = val1;
int value2 = val2;
=>
_value1 = val1;
_value2 = val2;
在changeValue局部变量,你有局部变量值1和值2。你的类有变量_value1和_value2。显然,这些名字是不同的。你想改变局部变量或类变量吗?
我要补充一点,你正在做C#的属性,所以你也有属性值1和值2,这也是不同于本地变量值1和值2(因为资本的V)
的输出“你想改变局部变量还是类变量?”老实说,我不知道。 – kidkuk 2014-09-12 16:48:03
它在我看来像你的任务是写一个拥有两个值的类,并可以打印总和。如果是这种情况,那么您想要将值存储在您的类属性Value1和Value2中(使用大写字母V)。局部变量value1和value2仅在构造函数changeValue正在运行时存在,然后它们消失。这些局部变量不会被printIt使用。如果仔细观察,您的printIt函数甚至不会尝试使用这些局部变量。它使用属性Value1和Value2(大写V)。 – 2014-09-12 19:02:27
你试图* *调试**吗? – Carsten 2014-09-12 16:33:26
你使用什么输入?你能给我们任何其他信息吗? – BradleyDotNET 2014-09-12 16:35:09
您从不将任何内容设置为Value1和Value2属性或其私有字段。您只是将值分配给构造函数中的私有字段。 – gmiley 2014-09-12 16:35:16