以下是我的C#书中的示例,我遇到了一个在Visual Studio中不起作用的书籍示例.它涉及创建自己的异常,尤其是阻止你取负数的平方根.但是,当我使用"throw new"创建NegativeNumberException时,我收到一条错误消息"无法找到类型或命名空间名称'NegativeNumberException'(您是否缺少using指令或程序集引用?)"
如果这不是正确的方法,我如何创建自己的例外?也许我的书已经过时了?这是代码:
class SquareRootTest
{
static void Main(string[] args)
{
bool continueLoop = true;
do
{
try
{
Console.Write("Enter a value to calculate the sqrt of: ");
double inputValue = Convert.ToDouble(Console.ReadLine());
double result = SquareRoot(inputValue);
Console.WriteLine("The sqrt of {0} is {1:F6)\n", inputValue, result);
continueLoop = false;
}
catch (FormatException formatException)
{
Console.WriteLine("\n" + formatException.Message);
Console.WriteLine("Enter a double value, doofus.\n");
}
catch (NegativeNumberException negativeNumberException)
{
Console.WriteLine("\n" + negativeNumberException.Message);
Console.WriteLine("Enter a non-negative value, doofus.\n");
}
} while (continueLoop);
}//end main …Run Code Online (Sandbox Code Playgroud) 不知道发生了什么.我查看了与此问题类似的其他帖子,但到目前为止还没有任何解决方案.这是包含错误的部分的注释的代码.有一次,它说!=不起作用,在其余的代码中,它说<<不起作用.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
//Hangman
int main()
{
//setup
vector<string> words;
words.push_back("GUITAR");
words.push_back("VIRGINIA");
words.push_back("LAPTOP");
words.push_back("WIFEY");
words.push_back("IPHONE");
srand(static_cast<unsigned int>(time(0))); //randomly select a word
random_shuffle(words.begin(), words.end());
const string THE_WORD = words[0];
const int MAX_WRONG = 8; //initialize wrong guesses
int wrong = 0;
string soFar(THE_WORD.size(), '-'); //initalize the word so far with dashes
string used = " "; //initalize letters used
cout << "Welcome to Hangman. Good luck!/n";
//game loop …Run Code Online (Sandbox Code Playgroud) 所以我要求用户一个月和一年.月份必须是十二个月中的一个,而一年必须是一个数字而不是字母.我试图弄清楚让程序说"输入错误,再试一次"的最佳方法,并再次提示他们输入.这是我正在为月份部分工作的代码部分.
public class MonthLength {
public static void main(String[] args) {
int month = 0;
// Prompt the user to enter a month
SimpleIO.prompt("Enter a month name: ");
String userInput = SimpleIO.readLine();
if (userInput.trim().toLowerCase().equals("january")) {
month = 1;
} else if (userInput.trim().toLowerCase().equals("february")) {
month = 2;
} else if (userInput.trim().toLowerCase().equals("march")) {
month = 3;
} else if (userInput.trim().toLowerCase().equals("april")) {
month = 4;
} else if (userInput.trim().toLowerCase().equals("may")) {
month = 5;
} else if (userInput.trim().toLowerCase().equals("june")) {
month = 6;
} else …Run Code Online (Sandbox Code Playgroud)