The code I have doesn't work with console.writeline
I'm not to use console.readline
[] tirePressure = new int [4];
string valueTestFail = "Get you tire check as soon as possible.";
Console.WriteLine("Let check your tires!\r\nPlease enter the pressure for the front right tire.");
string frontRightTire = Console.ReadLine();
while(!int.TryParse(frontRightTire, out tirePressure[0])){
Console.WriteLine(valueTestFail);
frontRightTire = Console.ReadLine();
} Console.WriteLine("Please Enter the pressure for the front left tire.");
string frontLeftTire = Console.ReadLine();
while(!int.TryParse(frontLeftTire, out tirePressure[1])){
Console.WriteLine(valueTestFail);
frontLeftTire = Console.ReadLine();
}
Console.WriteLine("Please Enter the pressure for your rear right tire.");
string rearRightTire = Console.ReadLine();
while(!int.TryParse(rearRightTire, out tirePressure[2])){
Console.WriteLine(valueTestFail);
rearRightTire = Console.ReadLine();
}
Console.WriteLine("Please enter the value of the rear left tire.");
string rearLeftTire = Console.ReadLine();
while(!int.TryParse(rearLeftTire, out tirePressure[3])){
Console.WriteLine(valueTestFail);
string rearLeftTire = Console.ReadLine();
}
if(tirePressure[0]==tirePressure[1] && tirePressure[2]==tirePressure[3]){
Console.WriteLine("The tires pass spec!");
}else{
Console.WriteLine("Get your tires checked out.");
}
The error code so long, the code just run the entire screen and I just want to console.writeline this code line
it sounds like you are trying to use a Windows .NET feature in Xamarin. I Googled "console writeline xamarin" and got some alternatives. Try System.Diagnostics.Debug.WriteLine(), for instance.
You might look at this URL, https://forums.xamarin.com/discussion/18387/equivalent-of-console-writeline, to see if the information there is able to help you out.
I've been using C# for over 10 years, I read through your C# code, and I don't see anything incorrect with it... if it's running on Windows. You might improve its style, but that's not what you're looking for, is it.
Related
I'm currently messing around with a Console application and I have some logic to get user input for 3 different things. I have the application designed so that the user can type 'Q' or 'q' at any time to exit the program. However, the way I am currently accomplishing this is through if statements after each user input (using the Console.ReadLine().)
A solution I thought of that would be better is to have a piece of code in one place that exits the program and is called automatically when the ReadLine() is executed and checks the input to see if it is 'q' or 'Q'. I was curious if there was any way to do something like this???
Here is the code I have now
Console.WriteLine("Please give me a source and destination directory...(Enter 'Q' anytime to exit)");
Console.Write("Enter source path: ");
_sourcePath = Console.ReadLine();
if (_sourcePath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Enter destination path: ");
_destinationPath = Console.ReadLine();
if (_destinationPath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = Console.ReadLine();
if (response.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}
It would be nice to remove the if blocks and just have the incoming value from the Console.ReadLine() checked when it is executed...
You can create a function to get the user's input and after the Console.ReadLine() just do any processing (exiting on 'q') on the input before returning it.
static void Main(string[] args)
{
Console.Write("Enter source path: ");
var _sourcePath = GetInput();
Console.Write("Enter destination path: ");
var _destinationPath = GetInput();
Console.Write("Do you want detailed information displayed during the copy process? ");
var response = GetInput();
var _detailedReport = response?.Substring(0, 1)
.Equals("y", StringComparison.CurrentCultureIgnoreCase);
}
private static string GetInput()
{
var input = Console.ReadLine();
if (input.Equals("q", StringComparison.CurrentCultureIgnoreCase))
Environment.Exit(Environment.ExitCode);
return input;
}
I'm afraid there's no direct way to hook into the ReadLine() call. Wrapping it all in your own method called 'ReadLine' could work though, say something like
static string ReadLine()
{
string line = Console.ReadLine();
if (line.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
//Other global stuff
return line;
}
//Elsewhere
Console.Write("Enter source path: ");
_sourcePath = ReadLine(); //Note: No 'Console.' beforehand. This is your method!
Console.Write("Enter destination path: ");
_destinationPath = ReadLine();
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = ReadLine();
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}
I'm from a python background and I'm finding it difficult to pick up the syntax in c#.
I'm trying to write code so that the program will continuously ask the user for input and it will echo it on the screen, but if the user input is 'exit' then it exits.
I tried
Console.WriteLine("Hello World!");
Console.Write("Enter some text: ");
string userinput = Console.ReadLine();
if (userinput == "exit")
{
Console.ReadKey();
}
else
{
Console.WriteLine(userinput);
But it doesn't achieve expected results
An if statement only executes once.
Since you're looking to take some action repeatedly, a do/while construct is more along the lines of what you need.
Something like this should at least get you started in the right direction:
string userinput;
do
{
Console.Write("Enter some text: ");
userinput = Console.ReadLine();
Console.WriteLine(userinput);
}
while (userinput != "exit");
The following code asks for your name and surname.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
int r = Console.Read();
Console.WriteLine("Your surname: " + r);
Console.ReadLine();
}
}
After entering the name, the program successfully displays your input. However, after entering a surname, the program stops immediately. From my understanding, Console.Read() should return an int value of the first character of the string I enter (ASCII code?).
Why does the program terminate right after Console.Read()? Shouldn't Console.ReadLine() ensure the program stays open? I am using Visual Studio 2012.
When you tell the console to enter your surname you are asking for a single character.
Console.Write("Enter your surname: ");
int r = Console.Read();
This surely should be a ReadLine followed by another ReadLine before exit. You are probably entering the first character (into Read), followed by subsequent characters, then hitting enter to accept the surname but you are actually on the ReadLine that will exit. So:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
string s = Console.ReadLine();
Console.WriteLine("Your name: " + s);
Console.Write("Enter your surname: ");
// change here
string surname = Console.ReadLine();
Console.WriteLine("Your surname: " + surname);
Console.ReadLine();
}
}
The program does not terminate after int r = Console.Read() for me.
Based on how the console application was run it will execute all the lines of code and then 'return'. Once done this will close the program as for all intents and purposes it has done what it needs to. It isn't going to sit around and be open when it has finished.
If you want it to keep the window open write Console.Readline() at the end and it will stay open, until some input has been done. I remember having this issue when I started out, and it's not a matter of the program closing unexpectedly, but rather you wanting to see the results in the console before it closes.
How to allow the user to press enter and for it to show incorrect instead of showing an error.
When in the program the user can press enter without entering info and the system crashes giving a System.FormatException error in which i have no idea how to fix.
Any help will be greatly appreciated and i thank you for reading.
double price, discount, answer, disprice, fahr, celc, celc2, fahr2;
char test, choice;
double Merc, mars, nept, uran, jup, sat, pluto, moon, venus;
do
{
Console.WriteLine("Choose from the following:");
Console.WriteLine("A: Mecury ");
Console.WriteLine("B: Venus ");
Console.WriteLine("C: Mars ");
Console.WriteLine("D: Jupitar");
Console.WriteLine("E: Saturn ");
Console.WriteLine("F: Uranus ");
Console.WriteLine("G: Neptune ");
Console.WriteLine("H: Pluto ");
Console.WriteLine("I: Moon ");
Console.WriteLine("Z: Help ");
Console.WriteLine("Q: to quit the program");
choice = char.Parse(Console.ReadLine());
switch (choice)
Instead of using char.Parse(), try char.TryParse():
....
Console.WriteLine("Q: to quit the program");
if (!char.TryParse(Console.ReadLine(), out choice)
{
continue; // Assuming your do/while loop will just loop. Might need to modify the while condition
}
switch (choice)
...
Parse will always throw if you pass it junk data.
You can catch it:
try
{
choice = char.Parse(...);
}
catch (FormatException ex)
{
//Display error
}
Or use TryParse which doesn't throw:
if (char.TryParse(..., out choice))
{
//Value in choice
}
else
{
//Parse Failed
}
Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");
//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
Console.WriteLine("The installation can not proceed.");
Console.Read();
return;
}
I have tried to input these:
y -> it gives me an empty string,
y(whitespace+y) -> it gives me the "y"
I have checked other similar posts, but none of them solves my problem.
The ReadLine() still skips the 1st input character.
UPDATE Solved, see below.
Suggested change:
Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");
Key points:
1) A string is probably the easiest type of console input to handle
2) Console input is line oriented - you must type "Enter" before the input becomes available to the program.
Thank you all for replying my post.
It's my bad that not taking consideration of the multi-thread feature in my code. I will try to explain where I was wrong in order to say thank you to all your replies.
BackgroundWorker worker = .....;
public static void Main(string[] args)
{
InitWorker();
Console.Read();
}
public static void InitWorker()
{
....
worker.RunWorkerAsync();
}
static void worker_DoWork(....)
{
.....this is where I wrote the code...
}
The problem was I started a sub-thread which runs asynchronously with the host thread. When the sub-thread ran to this line : var answer = Console.ReadLine();
the host thread ran to the Console.Read(); at the same time.
So what happened was it looked like I was inputting a character for var answer = Console.ReadLine();, but it actually fed to the Console.Read() which was running on the host thread and then it's the turn for the sub-thread to ReadLine(). When the sub-thread got the input from keyboard, the 1st inputted character had already been taken by the host thread and then the whole program finished and closed.
I hope my explanation is clear.
Basically you need to change Console.Read --> Console.ReadLine