How can I put my code into a method to work because now it has an error and I can't figure out how to solve it. In our exam we have to put every exercise into a method but now it says 'Cannot implicity convert type 'int' to 'string' when i try to return it (the 'n' is underlined).
public string FloydsTriangle(int n)
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
int count = 1;
for (int i = num; i > 0; i--)
{
for (int j = num; j >= i; j--)
{
Console.Write(count + " ");
count++;
}
Console.WriteLine();
}
Console.ReadLine();
return n;
}
Currently your code doesn't make a lot of sense, since you have a method which takes in an int, but does nothing with it, and returns a string, which is just the same int the user passed in only converted to a string (assuming you add .ToString() to the return value as mentioned in the other answer).
One idea to make this work would be to use the int argument as the basis for the triangle, and then to return a string representation of the triangle (instead of reading or writing anything to the console inside this method).
Note, I did not correct any of your existing code - I only changed how the method uses the input parameter and how it outputs the result:
public static string GetFloydsTriangle(int n)
{
int count = 1;
// Instead of writing strings to the console, we'll
// store them in this string and return it at the end
string triangle = string.Empty;
for (int i = n; i > 0; i--)
{
for (int j = n; j >= i; j--)
{
triangle = triangle + count + " ";
count++;
}
triangle = triangle + Environment.NewLine;
}
return triangle;
}
Then, to use the method, we will ask the user for a number in the Main method, then pass that to our method. Additionally, we'll capture the return value from the triangle method (which is our triangle string), and write that string to the console in the Main method.
This is a pretty standard way to write a helper method - it just does some calculations based on input data and returns a result (it doesn't interact with the user or UI).
Again, I am not correcting your code, only refactoring it to use the new method:
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
string triangle = GetFloydsTriangle(num);
Console.WriteLine(triangle);
Console.Write("\nDone! Press any key to exit...");
Console.ReadKey();
}
Your method specifies that you'll be passing back a string. You'll want to do something like:
return n.toString();
Otherwise you'll need to change your method to:
public int FloydsTriangle(int n)
Related
when I enter 1 for n
and 1111 for lines
the sum must be 1+1+1+1=4 but the output is 1.
THIS IS THE QUESTION...
you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.
using System;
namespace prom2
{
class Program
{
static void Main(string[] args)
{
int lines=0, sum = 0;
Console.Write("Enter a number of lines ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n&n>0&1000>n; i++)
{
Console.WriteLine("Enter line " + i + " numbers");
lines = int.Parse(Console.ReadLine());
lines = lines / 10;
sum += lines % 10;
Console.WriteLine("sum is " + sum);
}
}
}
}
Try this:
static void Main(string[] args)
{
int input;
bool times = true;
List<int> numbers = new List<int>();
while (times)
{
Console.Clear();
Console.WriteLine("Enter number: ");
var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
if (num)
{
numbers.Add(input);//only integers will be added to list
}
Console.Clear();
Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
var yesno = Console.ReadLine();//get answer from user
if (yesno.ToUpper().Trim() != "Y")//if N or anything else
{
//assume no
times = false;
}
Console.Clear();
}
var sum = numbers.Sum();
Console.WriteLine("Sum : " + sum.ToString());
Console.ReadLine();//just to pause screen
}
Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.
If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.
Edit
My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.
Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):
using System;
using Xunit;
namespace StackOverflow71442136SumDigits
{
public class UnitTest1
{
[Theory]
[InlineData("1", 1)]
[InlineData("12", 3)]
[InlineData("23", 5)]
[InlineData("1234", 10)]
[InlineData("123456789", 45)]
public void Test1(string line, int expectedSum)
{
var actualSum = this.SumTheDigits(line);
Assert.Equal(expectedSum, actualSum);
}
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
}
}
You might want to read How do I ask and answer homework questions?
My goal is to make a math expression interpreter with c#, for example if you type "A=3", it'll save the A as a dictionary key and 3 as its value, this program has more features so if you type "B=3" and then "A=B+3" and then "Show(A)", it must display "6" as the answer.
Everything is right until I type something like "A=10" "B=10" "C=A+B" and finally "Show(C)", because Variables' value are 2-digit (or more) numbers in this case, when producing the final result, numbers are saved in the string like "01+01" instead of "10+10" (because A and B values are 10 so A+B should be 10+10), so it's kinda reversed.
I tried to reverse the string and then evaluate the answer but that didn't work as well, simply it gives me "1+1" for some reason!
Notes:
expression evaluation is done by "return Convert.ToInt32(new DataTable().Compute(result, null));"
because strings are immutable in c#, when every expression like "A+B" or "3+5" comes in the method, I create a new empty string like (string result = " ";) and then with the help of "result = ValidExpression[i] + result.Remove(counter, 0);", I change the variables with values (note = if all the elements of input are numbers, answer is right) like "A" with "23" and put them in the new string and then evaluate the final string. But as I said, it saves the 23 as 32 so the answer will be wrong.
This is my code and the bug is probably in the LongProcessing method.
Thanks for your helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Data;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome To The Program\nCorrect Syntax:");
Console.WriteLine("A=10\nB=15\nC=A+B\nD=13/4-2+A-C+B\nShow(D)");
Console.WriteLine("\nEnter your input:");
Expression E = new Expression();
string expression = "start";
while (expression != "exit")
{
expression = Console.ReadLine();
// for show command
if (expression.Contains("Show") == true)
try { E.Show(expression[5]); }
catch (Exception e)
{
Console.WriteLine("input is not correct, Can not show anything. please try again");
}
if (E.Validation(expression) == false)
Console.WriteLine("input is not correct, please try again");
else
E.Processing(expression);
}
Console.ReadKey();
}
}
class Expression
{
public Dictionary<Char, String> Variables = new Dictionary<Char, String>();
public Expression()
{ }
public Boolean Validation(string expression)
{
// true if c is a letter or a decimal digit; otherwise, false && true if c is a decimal digit; otherwise, false.
if (!Char.IsLetterOrDigit(expression[0]) || Char.IsDigit(expression[0]))
return false;
else
return true;
}
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
// something is wrong in this method
public int LongProcessing(String ValidExpression)
{
string temp;
int counter = 0;
string result = " ";
for (int i = 0; i < ValidExpression.Length; i++)
{
//changing variables (letters) with values
if (Char.IsLetter(ValidExpression[i]))
{
if (Variables.ContainsKey(ValidExpression[i]))
{
Variables.TryGetValue(ValidExpression[i], out temp);
for (int j = 0; j < temp.Length; j++)
{
result = temp[j] + result.Remove(counter, 0);
counter++;
}
}
}
else
{
result = ValidExpression[i] + result.Remove(counter, 0);
counter++;
}
}
// checks if all of the string elements are numbers
if (ValidExpression.All(char.IsDigit))
return Convert.ToInt32(ValidExpression);
else
{
return Convert.ToInt32(new DataTable().Compute(result, null));
}
}
public void Show(Char ValidExpression)
{
Console.WriteLine(Variables[ValidExpression]);
}
}
}
This is broken:
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
temp.Remove(i, 0) is a non op, you might as well just write temp
So let's plot the loop:
Assume ValidExpression is "A=10"
Temp starts out as " "
First iteration, temp is "1 "
Second iteration, temp is "01 "
Any operation that works left to right through a string, character by character, pulling a character out and sticking it on the start of a growing string, will reverse the string
Perhaps you meant to not have a loop and instead do temp = ValidExpression.Substring(2) ?
Here are some suggestions:
Start by looking at the value of "temp" in "Processing". To assist in your debugging, add a "Console.WriteLine" statement.
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
{
temp = ValidExpression[i] + temp.Remove(i, 0);
Console.WriteLine(" temp: " + temp); //added for debugging
}
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
A couple of other things:
The user is never informed how to exit.
There is a class named "Expression" and a string variable named
"expression". This is likely to cause confusion.
You may also want to look at this post: how to convert a string to a mathematical expression programmatically
I have made bisection method program in C# Console Application. Bisection method works, but for function which is already written in the code. I want to edit program that user can input function which they want to use for bisection method. For example Console.ReadLine() for input "x^2 + x - 2" and then I want it automatically written after return in the code below.
static double Function(double x)
{
return x*x - 2;
} //this is Function which I used in code.
Here is the whole code. (as i mentioned it works for function which is written in static double Function(double x) part
using System;
namespace MPI
{
class MainClass
{
public static void Main(string[] args)
{
// in [a,b]
double inPoc = 0; //a
double inKraj = 0; //b
double sredina = 0;
double tacnost = 0;
Start:
int i = 0; //brojac
Console.Write("Unesite početak intervala: ");
inPoc = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite kraj intervala: ");
inKraj = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite tacnost: ");
tacnost = Convert.ToDouble(Console.ReadLine());
sredina = (inPoc + inKraj) / 2;
if (Function(inPoc) * Function(inKraj) < 0)
{
while ((Math.Abs(inPoc - inKraj)) > tacnost)
{
sredina = (inPoc + inKraj) / 2;
Console.WriteLine("trenutno X: " + sredina);
Console.WriteLine("Funkcija za trenutno x ima vrednost: " + Function(sredina));
Console.WriteLine("");
i++;
if (Function(sredina) < 0)
{
inPoc = sredina;
}
else
{
inKraj = sredina;
}
}
Console.WriteLine("X: " + sredina);
Console.WriteLine("Broj izvrsenih koraka je " + i);
}
else
{
Console.WriteLine("Krajevi intervala funkcije su istog znaka");
Console.WriteLine();
}
goto Start; //sluzi da vrati program na pocetak kako bi ga opet koristili
}
static double Function(double x)
{
return x*x - 2; //primer funkcije
}
}
}
Looks like this question is asking about the same.
There are two solutions to do this:
Solution 1 - just use Flee.
Copy-paste from documentation:
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;
variables.Add("a", 100);
variables.Add("b", 1);
variables.Add("c", 24);
IGenericExpression<bool> e = context.CompileGeneric<bool>("(a = 100 OR b > 0) AND c <> 2");
bool result = e.Evaluate();
So you can do the same, just change input/output types and put your input line into the CompileGeneric
Solution 2 - parse input string manually.
So question can be divided to the two parts:
How to parse input string into the expression tree.
How to execute this tree.
For the first item - please check reverse polish notation. It allows to construct computation stack.
Next you will able to compute your expression tree. Each operand (after trimming) will have variable or integer constant. So just replace variable to the actual value and just parse string to the integer.
My question is how to output things in the array in reverse order
grouped by two things with resorting only to the while-loop
(i.e., without for-loop and Reverse method, etc.)
I know that the second while-loop is not correct but I do not know how to modify it.
Thank you in advance for your suggestions.
Console.WriteLine("Please type four things.");
const int MAX_SIZE = 4;
string[] things = new string[MAX_SIZE];
int i = 0;
while (i < MAX_SIZE)
{
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
i = 0;
while (i < MAX_SIZE)
{
Console.Write(things[i] + ", ");
i--;
}
Try
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i] + ", ");
i--;
}
The reason I am using MAX_SIZE-1 is because arrays in C# are 0-based. The first element will always be in position 0. If the array has 4 elements, the final element will be in position 3.
If you want to print things in twos, you can just do the following:
i = MAX_SIZE - 1
while (i >= 0)
{
Console.Write(things[i-1] + ", " things[i]);
i -= 2;
}
Is there any reason you want to use a while loop instead of a for loop?
for(var i=0;i<MAX_SIZE;i++) {
Console.WriteLine("Please type the things.");
things[i] = Console.ReadLine();
i++;
}
for(var i=MAX_SIZE-1;i>=0;i--){
Console.Write(things[i] + ", ");
}
If I understand the task correctly, next code should work for you:
int i = things.Length - 1;
while(i > 0)
{
Console.Write("({0}, {1}) ", things[i], things[i - 1]);
i -= 2;
}
//in case the the list lenght is odd, output the last element without pair
if(i == 0)
{
Console.Write("({0})", things[i]);
}
if statement can be omitted if things list length is always even because it is required only if you need to pring the last (the first in things list) element, which has no pair.
I asked this question yesterday but it wasn't well received mainly due to how I asked it so ill try do better this time.
I have a string variable called message. lets say message equals "ABCDABCDABCDABCD"
now I need to do some processing on the characters in the string but not all at the same time, I want to access characters [0][4][8][12] on the first pass of the function, put each of these characters in a string and return it which is easy done if I pass an integer to my function lets say 4 and with in a for loop do
if(i % int == 0)
{
string += message[i];
}
this should return "AAAA"
the next time I call the function ill need elements [0][1], [4][5], [8][9], [12][13] and the time after that ill need [0][1][2], [4][5][6], [8][9][10], [12][13][14].
I need the characters returned in a string in the order they were taken, I could do this by changing my int I pass the function but then id need to call the function several times and do work on the returned strings to get them into the order they were taken, which I have already tried and it slowed my program down when dealing with large messages > 10k characters.
Please don't delete or put my question on hold, im quite happy to give more information on my problem if its not clear, ill seldom post to this site and usually try and find a solution myself, there are too many acceptance junkies on here for my liking. but I would appreciate some help from some of them regarding this.Thanks
Edit
I understand its not easy to figure it out and I have to say im not the best at describing it, its a vigenere cracker in WPF, I have done the kasiski examination on a piece of text and graphed out all the data, it finds the key length 90% of the time or gives me the best clue to what the key might be, now im calculating the frequency of bi,tri and quad grams of the message based on the data from the kasiski exam, lets say the key is 5 and the message is "ABCDABCDABCDABCD" im calculating probability on only the characters of the key Im changing so when I try key AAAAA im only wanting to calculate monograms on elements [0][4][9][14] of the message, ill run through 26 characters up to ZAAAA and take the most probable then I move onto element [1] of the key, lets say FAAAA gave the best score on the first element of the key. now I need elements [0][1],[5][6],[9][10][13][14] as im calculating probability on 2 pieces on the key FCAAA, so the length of the key and what key character im working on will determine what elements of the message ill be taking.
One-liner with LINQ (I use Batch extension from MoreLINQ, but you can use your own) which selects all required chars from input string:
string message = "ABCDABCDABCDABCD";
int size = 4;
int charsToTake = 2;
var characters = message.Batch(size).SelectMany(b => b.Take(charsToTake));
If you need result as string, you can easily create one:
var result = new String(characters.ToArray());
// ABABABAB
More efficient way - create your own method which will split string by substrings of required length:
public static IEnumerable<string> ToSubstrings(this string s, int length)
{
int index = 0;
while (index + length < s.Length)
{
yield return s.Substring(index, length);
index += length;
}
if (index < s.Length)
yield return s.Substring(index);
}
I would also create method for safe getting substring from start of string (to avoid annoying string length check and passing zero as start index):
public static string SubstringFromStart(this string s, int length)
{
return s.Substring(0, Math.Min(s.Length, length));
}
Now its very clear what you are doing:
var substrings = message.ToSubstrings(size)
.Select(s => s.SubstringFromStart(charsToTake));
var result = String.Concat(substrings);
Here is a simple program which does what you want, if I understand correctly:
static void Main(string[] args)
{
string data = "ABCDABCDABCDABCD";
Console.WriteLine(StrangeSubstring(data,4, 1));
// "AAAA"
Console.WriteLine(StrangeSubstring(data,4, 2));
// "ABABABAB"
Console.WriteLine(StrangeSubstring(data,4, 3));
// "ABCABCABCABC"
}
static string StrangeSubstring(string input, int modulo, int length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.Length; ++i)
{
if (i % modulo == 0)
{
for (int j = 0; j<length; ++j)
{
if (i+j < input.Length)
sb.Append(input[i+j]);
}
}
}
return sb.ToString();
}
My solution will be like this
static string MethodName(int range){
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < str.Length ; i++){
if(i % 4 == 0){
sb.Append(str[i]);
for(int j = i + 1 ; j <= i + range ; j ++){
if(j >= str.Length)
break;
sb.Append(str[j]);
}
}
}
return sb.ToString();
}
you can parse your string to a char array :
string message="ABCDABCDABCDABCD";
char[] myCharArray = message.ToCharArray();
string result="";
for(int i=0, i<myCharArray.Length -1 ; i++)
{
if(i%4 ==0)
result+=myCharArray[i];
}
EDIT 1 :
public string[] myfunction(char[] charArray)
{
List<string> result = new List<string>();
for(int i=0, i<charArray.length -1; i=i+4)
{
result.add(charArray[i]+charArray[i+1])
}
return result.toArray();
}
This is a recursive solution. In YourFunction, PatternLength is the length of the character pattern which is repeated (so, 4 for "ABCD"), Offset is where you start in the pattern (e.g. 0 if you start with "A") and SubstringLength is the number of characters.
The function call in Main will give you all "A". If you change SubstringLength to 2, it gives you all "AB". There is no error handling, make sure then PatternLength<=Offest+SubstringLength
namespace Foo
{
class Bar
{
static void Main(string[] args)
{
Console.WriteLine(YourFunction("ABCABCABCABCABCABCABC", 3, 0,1));
Console.ReadKey();
}
static string YourFunction(string SubString, int PatternLength, int Offset, int SubstringLength)
{
string result;
if (SubString.Length <= PatternLength)
{
result = SubString.Substring(Offset, SubstringLength);
}
else
{
result = YourFunction(SubString.Substring(PatternLength, (SubString.Length - PatternLength)), PatternLength, Offset, SubstringLength) + SubString.Substring(Offset, SubstringLength);
}
return result;
}
}
}