why won't this C# code run in the terminal?: using System; namespace Prog; class…
- User
why won't this C# code run in the terminal?: using System;
namespace Prog;
class GuessGame { static void Main(string[] args) {
}
void Rolling() { Random r = new Random(); int res = r.Next( 45); Console.WriteLine("Roll the Dice!"); String? Roll = Console.ReadLine();
if (Roll == "Roll") { Console.WriteLine(res); } Console.ReadKey();}
}
- Assistant
There are multiple issues with this C# code that prevent it from running in the terminal:
-
The namespace should not contain a semicolon. Instead of
namespace Prog;, it should benamespace Prog. -
The
Rollingmethod is not being called from theMainmethod. You need to either callRollingfromMainor move the code fromRollingdirectly intoMain. -
String?is not valid C#. It should bestring(lowercase).
Here's the corrected code:
using System; namespace Prog { class GuessGame { static void Main(string[] args) { Rolling(); } static void Rolling() { Random r = new Random(); int res = r.Next(45); Console.WriteLine("Roll the Dice!"); string Roll = Console.ReadLine(); if (Roll == "Roll") { Console.WriteLine(res); } Console.ReadKey(); } } }Note that I made the
Rollingmethod static so that it can be called fromMain. I also removed the unnecessary?fromstringand added ausingstatement forSystem. -
- User
Look at this C# code, how do I make the code loop itself where it always awaits the users input to "Roll the Dice!": using System;
namespace Prog;
class GuessGame { static void Main(string[] args) {
GuessGame g = new GuessGame(); g.Game(); Console.ReadKey();}
void Game() { Random r = new Random(); int res = r.Next( 45); Console.WriteLine("Roll the Dice!"); String Roll = Console.ReadLine();
if (Roll == "Roll") { Console.WriteLine(res); }}
}
- Assistant
To make the code loop so that it constantly awaits the user's input to "Roll the Dice!", you can use a
whileloop that keeps running until the user enters something other than "Roll". Here's the modified code:using System; namespace Prog { class GuessGame { static void Main(string[] args) { GuessGame g = new GuessGame(); g.Game(); Console.ReadKey(); } void Game() { Random r = new Random(); while (true) { Console.WriteLine("Roll the Dice!"); string Roll = Console.ReadLine(); if (Roll == "Roll") { int res = r.Next(45); Console.WriteLine(res); } else { break; } } } } }The
whileloop keeps running until the user enters something other than "Roll". Inside the loop, the program waits for the user's input, generates a random number if the input is "Roll", and prints the result. If the input is anything else, the loop breaks and the program exits.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.