Okay, so here is what I have, the console runs and accepts any number for the first input and outputs all the outputs but it skips the rest of the reads after the first one. I am new to C# and want to learn so I definetly feel like I am just missing something stupid here. Do not worry about the purpose as I only want help with this problem I am facing now.
Thanks guys,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stamps
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, and welcome to the U.S. Mail Stamp Printer. Now, to print the correct stamp for your postage, please enter the number of half ounces (so 1= .5 ounce, 2 = 1 ounce) your package will weigh \n");
double i = Console.Read();
Console.WriteLine("Thank you, now, will you be sending to zone 1, 2, or 3? Simply enter the zone number and press enter\n");
double z = Console.Read();
Console.WriteLine("Great! Now, last question before I print your stamp, will you be using Local Mail or Air Mail, use the number 1 for local and the number 2 for air.\n");
double m = Console.Read();
if (m == 2)
{
double m2 = .95;
}
else
{
double m2 = .49;
}
if( i == 1)
{
double i2 = 1;
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
The Console.Read method doesn't parse input, it only reads one character from the input stream.
Use the Console.ReadLine method and parse the string that you get:
double i = Double.Parse(Console.ReadLine());
or:
int z = Int32.Parse(Console.ReadLine());
If you want to handle invalid input you would use the TryParse methods, they will return a boolean that tell you if the parsing worked or not.
Side note: When you try to use the m2 and i2 variables you will notice that it doesn't exist. The variable is local for the code blocks in the if statement, so you need to declare it outside to be able to use it later:
double m2;
if (m == 2)
{
m2 = .95;
}
else
{
m2 = .49;
}
you can flush you console buffer or you can used console.readline().
For more information refer below post which give yours question answer.
http://stackoverflow.com/questions/7302544/flushing-system-console-read
Related
I'm wondering if someone can help me with decimals? Im going to make a program there can wright price and how much you paid, and then get a change back, but i need to add decimals. The decimals have to round up or down, so if it is 0,11 it goes to 0, if it is o,20 it goes to 0,25. So it will round up to either 0,25, 0,50, 0,75 and later on 1. The change have too also show in which cash you get back, so like 100 bucks, 500 bucks, 50 bucks if you know what i mean. I dont know how to do. This is how long i come:
using System;
namespace inlämninguno
{
class Program
{
// Starting point of my "Change" program
static void Main(string[] args)
{
Console.WriteLine(Subtract()); // adding a subract variable in the beginning of the code
Console.Read();
}
// Using the double datatype to for the decimals
public static double Subtract()
{
Console.WriteLine("Price?"); // how much it costs
string number1Input = Console.ReadLine();
Console.WriteLine("Paid?"); // how much the customer pays
string number2Input = Console.ReadLine();
double prince = Convert.ToDouble(number1Input);
double paid = Convert.ToDouble(number2Input);
// This is for the subtracting part
double num1 = double.Parse(number1Input);
double num2 = double.Parse(number2Input);
double result = num2 - num1; // this is so the console subtracts the values, have to put num2 first so the output isn't negative
Console.Write("Your change is " + result + ":"); // Output "Your change is ..."
return result; // A method that gives the right output of the code
}
}
}
Can someone please help me? Im stuck :D
I tried to convert to double and lots of stuff, but I don't know how to do now.
So previous I was having a ton of trouble with finding the difference between a randomly generated number and user input. I did a little search and found that I couldn't use Console.Read(); and that I actually had to use this int guess = Convert.ToInt32(Console.ReadLine()); While playing around with it i accidentally made it Convert.ToInt32(Console.Read()); which was in turn making the math completely wrong. Apologies if I'm not explaining myself effectively I'm new to coding and this was meant to be something to learn from. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Would you like to play the guessing game?");
string input = Console.ReadLine();
if (input.Equals("yes"))
{
Console.WriteLine("Alright! The rules are simple, i'll think of a number and you guess it!");
Console.WriteLine("Alright enter your guess: ");
int guess = Convert.ToInt32(Console.ReadLine());
Random rand = new Random();
int answer = rand.Next(1,11);
if (rand.Equals(guess))
{
Console.WriteLine("Congratulations you guessed correctly!");
}
else
{
Console.WriteLine("Aww you were so close! I guessed " + answer);
int difference = guess - answer;
Console.WriteLine("you were only " + Math.Abs(difference) + " away");
}
} else
{
Console.WriteLine("Closing application...");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
Console.Read()
Returns you the ascii value of a single character being input.
For example, entering 'A' would return 65. See here for a list of ascii codes. Note that the ascii value for 1 is actually 49.
Convert.ToInt32(Console.ReadLine());
Reads the entire line and tries to convert it to an integer.
Console.Read() will grab just one character and Console.ReadLine() takes the whole line or everything the user types until it found the "Enter" key pressed.
Becuase Console.Read reads in characters from the console. It returns, as an integer. So when you enter "yes" the output will be
121 = y
101 = e
115 = s
13 =
10 =
The final two characters (13 and 10) are equal to the Windows newline.
I'm trying to create a simple program to calculate an average. The user should enter a positive number, then I create a loop to sum from 0 to the number entered. Then the average is the total divided by the number entered.
Problem: When I enter a number, for example, 10, the variable becomes 58. To any value that I enter, it always adds 48. Anyone have a clue about this issue?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace inClass1
{
class Loops
{
static void Main(string[] args)
{
int total = 0;
int num;
Console.Write("Enter a positive number: ");
num = Convert.ToInt32(Console.Read());
for (int i = 0; i <= num; i++)
{
total = total + i;
}
double average = total / (double)num;
Console.WriteLine("The average is = " + average);
Console.ReadLine();
}
}
}
It's because Console.Read method reads the first char and returns its ASCII value. And it only reads one char, so you can't read more than one number at the same time. To fix that just use Console.ReadLine to take a string as input:
um = Convert.ToInt32(Console.ReadLine());
In case where the user inputs an invalid number this will fail. To prevent that you can look into int.TryParse method.
The problem is that you are using Console.Read.
That method returns a int, not a string. That int is the Unicode character code of the read character. The overload of Convert.ToInt32 that takes a int looks like this:
public static int ToInt32(int value) {
return value;
}
(Reference Source)
Which means that its just returning the passed value (instead of parsing). Unicode '1' is the number 49.
Instead, use Console.ReadLine which in addition to getting the whole input (not just the first character) will return a string, so that int.Parse is called on it instead of casting when you use Convert.ToInt32.
I am trying to create a console application which is basically a very simple version of a security measure used by some websites and banks etc.
The user will have declared a "Secret Word"(stored in a stringBuilder), after which, every time the user tries to access the program/website etc they have to enter character X of the word (X generated via a random). However, the random never selects the last character of the word.
Example: When i use a 2 letter Secret word, it will only ever select the first letter, when i have tried getting it to select the letter by other methods it thinks that there is a letter 0 which throws the whole application.
Why is the final character never being selected? please help (new to c#)
Code Below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace randomCharSelecter
{
class Program
{
static void Main(string[] args)
{
StringBuilder stringBuilder = new StringBuilder();
Console.WriteLine("Please Enter Your Secret Word");
stringBuilder.Append(Console.ReadLine());
EnterInput:
Random rndSelect = new Random();
int randomChar1 = rndSelect.Next(1, (stringBuilder.Length));
Console.WriteLine("Please enter character {0} of your secret word", randomChar1);
string userInput = Console.ReadLine();
if (userInput == (Convert.ToString(stringBuilder).Substring(randomChar1 - 1, 1)))
Console.WriteLine("Correct!");
else
{
Console.WriteLine("Incorrect! Please try again");
goto EnterInput;
}
Console.ReadLine();
}
}
}
This is the expected behavior. From the documentation:
Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.
In other words if you want a random integer between 1 and stringBuilder.Length, inclusive (that is, that the result could possibly equal stringBuilder.Length), you need to use:
int randomChar1 = rndSelect.Next(1, stringBuilder.Length + 1);
Alternatively, you could simply modify the code to make use of zero-based indexing:
int randomChar1 = rndSelect.Next(0, stringBuilder.Length);
...
if (userInput == (Convert.ToString(stringBuilder).Substring(randomChar1, 1)))
Console.WriteLine("Correct!");
Your problem is that the second value of Random.Next(int val1, int val2) is end-exclusive. So you'll end up having to do stringBuilder.Length + 1
Source: http://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx
I am trying to make a command line program that will ask if fast and long you want it to beep. I keep getting System.FormatException on the code below. I get the problem right after Console.WriteLine("how many times should i beep?");. I've found a fix by putting a console.read();//pause right after this line.
My question is what am I doing wrong? or am I suppose to have the pause after that line?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("how fast would you like the sounds to play?");
Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
string choice = Console.ReadLine();
int speed = Convert.ToInt32(choice);
Console.Write(speed);
Console.Read();//pause
Console.WriteLine("how many times should i beep?");
string choice2 = Console.ReadLine();
int j = Convert.ToInt32(choice2);
Console.Write(j);
Console.Read();//pause
for (int i = 0 ; i < j; i++)
{
Console.Beep(1000, speed);
}
}
}
My psychic debugging skills tell me that it's this line throwing the exception:
int j = Convert.ToInt32(choice2);
Putting the Console.Read() in like you mentioned before that causes that line not to execute immediately and delaying the throwing of the exception.
If you input something that isn't an integer on this line:
string choice2 = Console.ReadLine();
You will get a FormatException on the following Convert.ToInt32 call.
See the documentation for Convert.ToInt32 where it tells you a FormatException is thrown when the value you pass does not consist of an optional sign followed by a sequence of digits (0 through 9).
To solve your issue, use Int32.TryParse (or just make sure you enter a valid integer). That will return a boolean indicating the success or failure of the parsing rather than throwing an exception.
Also, welcome to StackOverflow! Be sure to upvote answers you find helpful and accept the one that best resolves your question.
why are those extra Console.Read() in there? They are breaking your program, because the user will press return too many times
Console.WriteLine("how fast would you like the sounds to play?");
Console.WriteLine("70 = fast and 300 = slow can pick any number inbetween");
string choice = Console.ReadLine();
int speed = Convert.ToInt32(choice);
Console.WriteLine(speed);
Console.WriteLine("how many times should i beep?");
string choice2 = Console.ReadLine();
int j = Convert.ToInt32(choice2);
Console.Write(j);
for (int i = 0; i < j; i++)
{
Console.Beep(1000, speed);
}
Actually, all you need to do is remove those Read() pauses you threw in. I'd probably also change the Write() calls to WriteLine() calls.
You can also change the Read() calls to ReadLine() calls, if you insist on "pausing" there.
Try this:
Console.Read();
string choice2 = Console.ReadLine();