This question already has answers here:
Input string was not in a correct format
(9 answers)
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
I am currently learning the C # language. I have the following task:
Write program that:
Reads an input of integer numbers and adds them to a stack
Reads commands until "end" is received
Prints the sum of the remaining elements of the stack
Input
On the first line you will receive an array of integers
On the next lines,
until the "end" command is given, you will receive commands - a single command and one or two numbers after the command, depending on what command you are given
If the command is "add", you will always receive exactly two numbers after the command which you need to add in the stack
If the command is "remove",
you will always receive exactly one number after the command which represents the count of the numbers you need to remove from the stack. If there are not enough elements skip the command.
Output
When the "end" command is received, you need to Print the sum of the remaining elements in the stack
Input
1 2 3 4
adD 5 6
REmove 3
eNd
Output
Sum: 6
input:
3 5 8 4 1 9
add 19 32
remove 10
add 89 22
remove 4
remove 3
end
Output:
Sum: 16
I wrote this code. From the beginning it works, I enter a number of numbers and put them in the stack without any problems. From now on, after entering what I want to do "add", "remove" or "end", an error appears after adding numbers. after I decide to add an element the program allows me to enter numbers indefinitely until I try to change the addition of numbers with one of the other two options I get this error: System.FormatException: 'Input string was not in a correct format.'
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Stack_Sum
{
class Program
{
static void Main(string[] args)
{
Stack<int> numbers = new Stack<int>();
string input = Console.ReadLine();
string[] number = Regex.Split(input, #"\D+");
foreach (string value in number)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
numbers.Push(i);
}
}
string option = Console.ReadLine();
while (true)
{
switch (option.ToLower())
{
case "add":
int addToStack = Int32.Parse(Console.ReadLine());
for (int i = 0; i < 2; i++)
{
numbers.Push(addToStack);
}
continue;
case "remove":
int popItem = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < popItem; i++)
{
numbers.Pop();
}
continue;
case "end":
foreach (var Stack_Sum in numbers)
{
int sum = 0;
sum += Stack_Sum;
}
break;
}
}
}
}
}
You're only asking for the option selection once, before the while(true) loop:
string option = Console.ReadLine();
After that, you treat all user input as integers, so there's no opportunity for the user (you) to change the option. One easy fix is to place that line inside the loop, preferably with some more instructions:
//... Your code...
while(true)
{
Console.Write("Add, Remove, End: “);
string option = Console.ReadLine();
switch(option.ToLower())
{
//... Your code...
}
}
Now, I'm not convinced that the rest of your program works properly, but that's another story. You can debug it with breakpoints once you get over this hurdle.
Related
This question already has answers here:
int.Parse, Input string was not in a correct format
(7 answers)
Closed 2 years ago.
Here is my code :
using System;
namespace CappedSum
{
class Program
{
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;
while (sum<sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
if (sum + number < sumLimit)
{
sum += number;
count++;
}
else if (sum + number > sumLimit)
{
Console.WriteLine(sum + " " + count);
}
}
}
}
}
I had to write a console application that reads from the keyboard a list of numbers until their sum reaches a certain limit also entered by the user.
The limit is given on the first line, and on the next lines will be the list of numbers which has to be added. The program will stop reading when the sum of the numbers entered so far exceeds the limit and will display the last amount that did not exceed the limit, as well as how many numbers were needed to calculate it.
for example : if I enter 10 (which is the limit) then I enter 2,3,2,6. The result will be 7 (which is the last amount that did not exceed the limit) and 3 (which represents how many numbers needed to calculate it).
Try out Int32.Parse instead of Convert.ToInt32. Also, a really basic I use sometimes to debug my same mistakes, is to write MessageBoxes after specific instructions, so if they do not work I never get to the message, viceversa if the message shows I know that works. I'd put two Messageboxes after the Int32.Parse(Console.Readline()) being like MessageBox.Show(sumlimit/number.ToString());. This way you know how far the code works.
I am creating for my studies a program a simple one. In this program I need to make a sentence of 10 words. After the last input however I want to make it stop. So what I tried is this:
Create an empty string called textt, use a while loop since I make it always true it will proceed, create a string with the assignement that shows up in the program to the user aSentence its called, take an int named count and give it the value of 0, then I start my for loop I use the for loop cause I can add a condition and iterator so it stops and of course the initializer.
In the for loop I: print out the aSentence ( the user will read this ), I put a string called input and let the user put in a word ( I'm a beginner I do not know if how to make an error if the user put two words but thats not the assignment now ), I put the string textt since they are immutable but not in here and I add " " for create empty space and of course the input. Then I print out the textt what the user wrote down and I increment ( if I say this correctly ) with i++.
Then I start an if statement which says that if i ( see my for loop ) is equal == to 9 cause I increment this in my for loop it should print out End of the sentence, show the whole textt and then break.
However for some reason the loop is infinite everytime you input something. And the line End of the sentence will show up now and then and now when the loop should be finished at 9.
My question how do I fix this to make sure the sentencenends when 10 words have been inputted by the user and the End of the sentence pops up at exactly 10 input words.
using System;
namespace Opgave_10_woorden_invoegen_in_1_string_plakken
{
class Program
{
static void Main(string[] args)
{
//Create a program that stops after input of 10 words
string textt = "";
while (true)
{
string aSentence = new string("We are making a sentence of 10 words.");
int count = 0;
for (int i = 0; i < 9; i++)
{
Console.WriteLine(aSentence);
string input = Console.ReadLine();
textt = textt + " " + input;
Console.WriteLine(textt, i++);
if (i == 9)
{
Console.WriteLine("End of the sentence", textt);
break;
}
}
}
}
}
}
Combining my comments into an answer:
while(true) will run forever (unless some code calls break). Your inner for loop should work fine - why not just remove the while loop?
And your for loop condition should be < 10, since you want 10 items and the count is starting at 0. And you don't need a break statement inside a for loop, since the condition is built-in at the for statement.
There's also a problem in that you're incrementing i twice: once in the for statement iterator and again in the body of the for loop, so i will become 9 in only 5 iterations. Remove the inner increment. See the for statement documentation here.
Also, you don't need to do call a string constructor for the string assignment (does that even compile?). Just assign the string directly: string aSentance = "We are making a sentence of 10 words.";
Finally, you might look at the documentation for Console.WriteLine. The second variable you're passing to it isn't likely what you think it should be.
To put this all into a sample:
static void Main()
{
//Create a program that stops after input of 10 words
string textt = "";
string aSentence = "We are making a sentence of 10 words.";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(aSentence);
textt = textt + " " + Console.ReadLine();
Console.WriteLine(textt);
}
Console.WriteLine("End of the sentence");
Console.ReadKey();
}
You while (true) statement means that your loop runs forever.
You are trying to break out of this by using break. But as this is executed inside an inner for loop, then it will only break out of that inner loop and not your outer while loop, which is what you intend and expect.
You have no need for the outer while loop, so simply removing it will solve the problem.
If you want 10 inputs then you also need to change your for loop to run for 10 iterations, not 9 as your currently have.
Also, you should use StringBuilder class when concatenating strings together so many times, as it is more efficient.
See: https://www.dotnetperls.com/stringbuilder for more details
This is for a homework assignment which I have been working on for quite a while now but have not been able to figure out. Here are the exact instructions from my teacher if you need them; it is at number five that I am stuck:
(1) Have the user enter a sentence that they want to have encoded.
(2) If the number of characters in the message is odd, concatenate a space (" ") to their message so that our message will always be an even number of letters.
(3) Now create a new char[], call it unCoded where each element is a letter from your secret message.
(4) Now create an empty second char[], call it coded, and define its length equal to the length of the other char[], unCoded.
(5) Now write the values from the uncoded array into the coded array, but flipping each 2 letters.
(6) Then write out the original uncoded message.
(7) Then write out the new coded message.
He also said step 5 must be done in a loop.
Any help would be appreciated, thanks.
What I have so far:
static void Main(string[] args)
{
Console.WriteLine("Enter the sentence you want encoded: ");
string userInput = Console.ReadLine();
int remainder = userInput.Length % 2;
if (remainder!=0)
{
userInput = userInput + " ";
}
char[] unCoded = userInput.ToArray();
char[] coded=unCoded;
//coded.Length = unCoded.Length;
for (int i = 0; i < unCoded.Length; i=i+2)
{
coded[0] = unCoded[1];
coded[1] = unCoded[0];
}
string encoded = new string(coded);
Console.WriteLine("{0}", userInput);
Console.WriteLine("{0}", encoded);
Console.ReadKey();
}
Well, in your loop you don't use the loop parameter, so you just change up the first two values several times. Consider what you are doing in your loop to be the first step of what you actually want to achieve. Do it using the "i" variable and knowing that it's first value is 0. Then when i "grows", the loop will do the same for the next two values.
so just put i in place of 0 and i+1 in place of 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am very new to c# and I don't get it very quickly. If you can explain how and why like your talking to a 3yr old that would be great!!!
how do you make (enter the amount (-1 to stop)) repeat and end up with a total of all amounts entered?
Luckily, my 3-year old is sitting right here, so I had him write it out :)
var total = 0; // This will hold the sum of all entries
var result = 0; // This will hold the current entry
// This condition will loop until the user enters -1
while (result != -1)
{
// Write the prompt out to the console window
Console.Write("Enter the amount (-1 to stop): ");
// Capture the user input (which is a string)
var input = Console.ReadLine();
// Try to parse the input into an integer (if TryParse succeeds,
// then 'result' will contain the integer they entered)
if (int.TryParse(input, out result))
{
// If the user didn't enter -1, add the result to the total
if (result != -1) total += result;
}
else
{
// If we get in here, then TryParse failed, so let the user know.
Console.WriteLine("{0} is not a valid amount.", input);
}
}
// If we get here, it means the user entered -1 and we exited the while loop
Console.WriteLine("The total of your entries is: {0}", total);
We are calling it loops, little boy :P
UPDATE I dont know if i understood you, but now the code writes sum each time, and if you enter for example -5 it will be sum = sum - 5
class Program
{
static void Main(string[] args)
{
// thoose are variables, and they are storing data
int input = 0; // input integer number
int sum = 0; // sum of all numbers
while (true) //Infinite loop (executes undereneath code until true=true)
{
input = int.Parse(Console.ReadLine()); // read the line from user, parse to int, save to input variable
if (input == -1) break; // if integer input is -1, it stops looping (the loop breaks) and GOES (two lines down)
sum = sum+ input; // summing all input (short version -> s+=input)
Console.WriteLine("Actual Sum: "+sum); // HERE IS THE UPDATE
}
//HERE
Console.WriteLine("Your final sum is: " + s);
}
}
I've developed a new found interest in programming however I have had some problems. I have tried to make a simple program in which a user enters 10 numbers, if the number is 0 it will stop, then adds those numbers to a list then prints the list at the end. However, my program only asks for 4 numbers before stopping, it doesn't stop when 0 is entered and the "Enter a number message" at the start prints 3 times each time it goes round the loop.
Any help would be appreciated
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args) {
// I want to make a list
// keep asking the user for values
// which will then add those values onto the list
// then print the list
// create a list
List<int> list = new List<int>();
int count = 0;
while (count < 10) {
Console.WriteLine("Enter a value to add to the list");
int number = Console.Read();
list.Add(number);
if (number == 0) {
break;
}
count++;
}
Console.WriteLine("The final list looks like this");
foreach (int number in list) {
Console.WriteLine(number);
Console.ReadLine();
}
}
}
}
The problem is with Console.Read() - It reads a byte rather than a string that should be converted into int in your case.
What you're looking for is Console.ReadLine(), surrounded with int.Parse(). Something like this:
int number = int.Parse(Console.ReadLine());