我正在尝试创建一个用C#测试信用评分范围的类。希望如果在if else语句中选择范围,那么我可以返回有效或无效。
该类正在从获取并存储该类的另一个调用中获取分数,然后将运行该分数并验证是否验证,是否在300到850的范围内,但是在我完成此VS之前我在向我大吼大叫。
谢谢
using System;
namespace ConsoleApplication34
{
//test score and returns valid if below 300 or above 850.
//
class CreditScoreEngine
{
public int TestScore()
{
int score = 0;
if (score >= 300 && score <= 850)
score = Convert.ToString("valid")
else (string = "invalid")
}
}
}
答案 0 :(得分:1)
这段代码有几件事情非常错误。
score
定义为int。然后尝试通过Convert.ToString
为其分配一个值,该值返回一个字符串。编译器不允许您将一种类型的值分配给完全不相关类型的变量。else
不接受条件,因为它在前一个if
内的条件返回false时运行。您要么使用花括号而不是括号,要么意味着使用else if
。string
是一种类型,而不是变量。说string = ???
没有任何语法意义 - 你不能重新分配一种类型。 (也许你的意思是score
而不是string
。)else if
,则需要比较运算符==
而不是赋值运算符=
。一种简单的方法可以记住哪个是=
表示“等于”而==
表示“等于”(较长的运算符具有较长的含义)。else if
,那么else if
需要一个正文。score
的值硬编码为0,因此此函数不会测试任何内容。您需要通过Console.ReadLine
向此函数添加输入,或者更改函数以获取参数。bool
。如果函数本身可以运行,它的返回值也可能为void
。但是你已经指定它的返回值为int
,除非有一些你忘记提及的东西没有任何意义。 例如,您想要的代码可能如下所示:
public bool TestScore(int score)
{
if (score >= 300 && score <= 850)
{
return true;
}
else
{
return false;
}
}
或者,它看起来像这样:
public void TestScore()
{
string input = Console.ReadLine();
int score;
if (int.TryParse(input, out score))
{
if (score >= 300 && score <= 850)
{
Console.WriteLine("The score passes.");
}
else
{
Console.WriteLine("The score fails.");
}
}
else
{
Console.WriteLine("The score is not in the correct format.");
}
}
答案 1 :(得分:0)
您的问题难以理解,您的示例代码没有逻辑意义。但是,我认为你正在尝试做这样的事情:
public bool isValid(int score) { return score >= 300 && score <= 580;}
答案 2 :(得分:0)
//rewrite the code using this
public string TestScore(int score)
{
//I believe it would be more appropiate if you would return a boolean
//instead of a string.
return (score>=300 && score<=850)?"valid":"invalid";
}