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();
Related
today I have an issue which is driving me up a wall. I am a novice programmer, currently learning the basics of C#, after learning Java.
Today, I was working on a practice example when I encountered this problem:
Code Running
This is a screenshot of my code running, and I have left a print statement inside the loop to show me what my index variable is doing. As you can see, it is incrementing more than once per each execution of the loop. I have also gotten the same results when using a while loop, and in other projects.
Here is the code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
I cannot really proceed with this assignment until I can figure out what is causing this issue. Thanks!
try ReadLine() instead of Read() like
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}
Hi Welcome to the wonderful world of C#
Your problem here is Console.Read()
Console.Read() will give you an int of the character 4 which is your first typed character. And that character will be 52.
So it will loop 52 times.
Instead of Console.Read() use Console.ReadLine()
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 am trying to solve this problem https://open.kattis.com/problems/simon on open.kattis.com and I have this piece of code and it does exactly what it is supposed to, if the string starts with simon says then it the rest of the string is outputed, and if it doesn't start with simon says then output a blank line.
using System;
namespace Tester
{
internal class Program
{
private static void Main(string[] args)
{
int lines = int.Parse(Console.ReadLine());
string[] inputs = new string[lines];
for (int i = 0; i < lines; i++)
{
inputs[i] = Console.ReadLine().ToLower();
if (inputs[i].StartsWith("simon says"))
inputs[i] = inputs[i].Substring(10);
else
inputs[i] = "";
}
for (int i = 0; i < lines; i++)
Console.WriteLine(inputs[i]);
}
}
}
Input:
4
simon says write a program
print some output
simon whispers do not stress
simon says get balloons
Output:
write a program
get balloons
The testcase works fine in VS. No exceptions there.
But when I submit it for testing, I get Runtime Error. Any ideas what it could be caused by? The platform says that it is an uncaught exception, but does not specify what exception
Edit: So now I have wrong answer although the output is correct when testing in VS.
Edit: Test case works in kattis.com but not their hidden test case
Change your if statement to if (inputs[i].StartsWith("simon says")). It doesn't depend on the string's length.
There are a variety of bugs in the code. The first thing to remember when posting questions about code not working is to tell us which line is blowing up, what (if any) inputs you've given the application and (most importantly) what exception you are getting.
int lines = Convert.ToInt32(Console.ReadLine());
// will fail when input isn't numeric
if (inputs[i].Substring(0, 10) == "simon says")
//will fail when input is less than 10 characters
inputs[i] = inputs[i].Substring(11);
//You should use 10, not 11 since the next input after "simon says" could be in the 10th index position.
//will fail if user only types "simon says" (no 12th character)
Try this.
private static void Main(string[] args)
{
int testCases = Int32.Parse(Console.ReadLine());
var print = new List<string>();
while (testCases-- > 0)
{
var line = Console.ReadLine();
print.Add(line.StartsWith("simon says ") ? line.Remove(0, 11) : "");
}
foreach (var simonSaid in print)
Console.WriteLine(simonSaid);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lotto
{
class Program
{
static void Main(string[] args)
{
char k = 'l';
while (!(k == 'k'))
{
Random rnd = new Random();
int[] tablica = new int[6];
for (int i = 0; i < 6; i++)
{
tablica[i] = 0;
}
for (int i = 0, z; i < 6; i++)
{
{
z = rnd.Next(1, 49);
while (tablica.Contains(z))
{
z = rnd.Next(1, 49);
}
tablica[i] = z;
}
}
Array.Sort(tablica);
foreach (int q in tablica)
{
Console.Write(q);
Console.Write(", ");
}
k = Convert.ToChar(Console.Read()) ;
Console.WriteLine("\n\n\n");
}
}
}
}
It works alright. When I use the step by step clickage (F10 in visual studio), it runs fine. But when I run it normally, then after the
k=Convert.ToChar(Console.Read());
when I supply 'k', the program stops, as intended.
when I supply nothing, it does the
foreach (int q in tablica)
{
Console.Write(q);
Console.Write(", ");
}
k = Convert.ToChar(Console.Read()) ;
Console.WriteLine("\n\n\n");
two times, and when I supply anything other than 'k' it does it three times. What.The.Hell.
Console.Read reads a single character at a time from the input stream (doc). When you press enter you are supplying two characters: \r then \n, so there are two characters to read before pausing for further user input.
I'm confused how it ran fine when you used F10 as I did this to see what was looping, I just so happened to use Enter when supplying "nothing" and saw the characters pop through.
Did you try capturing the input from Console.Read() and see what it is giving you? It might be something to do with a control character being read in, and it not being able to convert to char properly.
Also, completely aside, I would recommend reformatting your code (you have superfluous "{}" in there in the second for loop). Also, it is always good practice to give meaningful names to your variables. i, j, k, etc. have no inherent meaning. It will just be easier to refactor/maintaining your code in the future.
I didn't take a real close look at the rest of your code, but I'm guessing there are shorter/simpler ways to do a lot of it. This many for/foreach/while loop in one method has a code smell.
By using Console.Read(), you are actually getting your input plus "\r\n",so when you use ENTER you just get "\r\n"(2 chars), when you input a char"m", your input is "m\r\n"(3 chars), that's the reason why there is a "one" difference.
Besides, why use int i = 0, z;? the , z does not mean anything here for this is C++ usage.
I am new to programming and I have a project in my Algorithm class. What we have to do is decide on a problem and solve it. We haven't learnt much more than string, char and WriteLine. We did add a couple of things as you will see soon!
I decided that what I want to solve this: The user inserts a word, no matter how long and the program will automatically make the first letter a capital letter. So far this is what I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
start:
Console.WriteLine("Please enter a word below:");
Console.WriteLine("");
string str = Console.ReadLine();
char char1;
if (str[0] >= 97)
{
char1 = (char)(str[0] - 32);
}
else
{
char1 = (char)(str[0] + 32);
}
char char2 = (char)(str[1]);
char char3 = (char)(str[2]);
char char4 = (char)(str[3]);
char char5 = (char)(str[4]);
Console.WriteLine("");
Console.Write(char1);
Console.Write(char2);
Console.Write(char3);
Console.Write(char4);
Console.WriteLine(char5);
goto start;
}
}
}
The problem with that code is that any word with less than 5 letters will make the program crash. Anything with more than 5 letters will just be cut at the fifth letter... I was told that using arrays should solve this problem. Seeing as I am a total newbie at this, I would need this to be broken down and be as simply told as possible!
Any help getting this to work would be very appreciated.
Thanks :)
Console.WriteLine("Enter a word:");
string str = Console.ReadLine();
Console.WriteLine(str[0].ToString().ToUpper() + str.Substring(1));
This will work.
Or... if you need to go through the entire string and find the first actual alphabetical character, you can do the following:
Console.WriteLine("Please enter a word:");
string s = Console.ReadLine();
bool found = false;
char[] chars = new char[s.Length];
for (int i = 0; i < s.Length; i++)
{
if (Char.IsLetter(s[i]) && !found)
{
chars[i] = s[i].ToString().ToUpper()[0];
found = true;
}
else
{
chars[i] = s[i];
}
}
s = new String(chars);
Console.WriteLine(s);
Use a for loop like this after writing char1 to the Console:
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)// Start at 1 to skip char1
{
Console.Write(str[i]);
}
}
There are some methods you can call on string that will be helpful:
Substring
ToUpper
In fact, you don't need to worry about characters; this problem can be solved using only strings.
Also take care to check that your code handles the case where the string is empty (using an if statement), which will happen if the user just presses Enter without typing anything.
You're taking an algorithms class and they make you choose a problem to solve? Sounds dangerous for someone learning.
Console.WriteLine("Please enter a word below:");
Console.WriteLine("");
string inputString = Console.ReadLine(); // try to use meaningful variable names
// shorthand for the if ... else block:
// type variableName = (true/false condition) ? "is true" : "is false";
char firstChar = inputString[0] >= 97 ? (char)(inputString[0] - 32) : (char)(inputString[0] + 32);
Console.WriteLine("");
Console.Write(firstChar);
for (int i = 1; i < inputString.Length; i++) // skip firstChar
{
Console.Write(inputString[i]);
}
As others have mentioned, you need to use a loop for this if you want anything resembling a general solution.
Also, you'll want to avoid using goto statements. There are many reasons, one being that they (in my opinion) make code difficult to read and maintain.
Additionally, if your code had worked as written, it would never end. Your program, as written would execute, then begin again, never stopping. If you want this sort of behavior, then you should wrap your code in an infinite loop which exits upon some condition. This might look something like:
bool keepRunning = true;
while(keepRunning){
//code here
Console.Write("go again? (y/n) ");
keepRunning = (string)(Console.ReadLine()).equals("y") ? false : true;
}
On that last statement, I forget if you need to cast the output of ReadLine to a string before calling the .equals method... I don't have my IDE up. i think you get the idea.
edit: I saw another response that was just posed about using the .ToUpper method. I thought of this but assumed maybe you needed to use the char type.