I'm currently writing a program that takes a persons name and 5 variables. Then with those 5 variables I'm tasked with finding the avg/sample variance. My current code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userName = "";
string variables = "";
int[] vars = parseVariableString(variables);
vars = new int[5];
int sum = 0;
Console.Write("Please enter your name: ", userName);
userName = Console.ReadLine();
Console.ReadLine();
Console.Write("Please enter 5 numbers with a space or coma inbetween: ", vars);
for (int i = 0; i < vars.Length; i++)
{
int number = vars[i];
sum += number;
}
float avg = sum/(float)vars.Length;
float variance = 0;
for (int i = 0; i < vars.Length; i++)
{
int number = vars[i];
float f = number - avg;
variance += (float)Math.Pow(f, 2);
}
float sv = variance / (vars.Length - 1);
Console.Write(" Your name is: ", userName);
Console.ReadLine();
Console.Write("The average of your numbers is: ", avg);
Console.ReadLine();
Console.Write("The sample variance of your numbers is: ", sv);
Console.ReadKey();
}
private static int[] parseVariableString(String variables)
{
String[] varArray = variables.Split(' ', ',');
int[] intArray = new int[varArray.Length];
for (int i = 0; i < varArray.Length; i++)
{
String variable = varArray[i];
int integer = Convert.ToInt32(variable);
intArray[i] = integer;
}
return intArray;
}
}
}
I'm getting the
Input string was not in correct format
error at int integer = Convert.ToInt32(variable);. I'm not understanding why exactly I'm getting this error. I looked online for what it means, a lot of people say to use an int.parse but from what I read you get this because the variable doesn't recognize that there is a value associated with it. Any help would be greatly appreciated.
string variables = "";
int[] vars = parseVariableString(variables);
You're declaring an empty string, and then trying to convert that string into an int.
private static int[] parseVariableString(String variables)
{
String[] varArray = variables.Split(' ', ',');
int[] intArray = new int[varArray.Length];
for (int i = 0; i < varArray.Length; i++)
{
String variable = varArray[i];
int integer = Convert.ToInt32(variable);
intArray[i] = integer;
}
return intArray;
}
As well as when you're passing in an empty string, there's nothing to split, and thus your array is empty.
Related
So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
class Program
{
void Heapify(List<int> array, int i, int n)
{
int largest, temp;
int parent = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && array[left] > array[parent])
{
largest = left;
}
else
{
largest = parent;
}
if (right < n && array[right] > array[largest])
{
largest = right;
}
if (largest != i)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, largest, n);
}
}
void BuildHeap(List<int> array, int n)
{
int i;
for (i = (n - 1) / 2; i >= 0; i--)
{
Heapify(array, i, n);
}
}
void HeapSort(List<int> array, int n)
{
int i, temp;
for (i = n - 1; i >= 0; i--)
{
temp = array[0];
array[0] = array[n - 1];
array[n - 1] = temp;
n = n - 1;
Heapify(array, 0, n);
Console.WriteLine(string.Join(" ", array));
}
}
static void Main(string[] args)
{
int n = 0;
Program A = new Program();
StreamReader myFile =
new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for (int j = 0; j < listInts.Length; j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
A.BuildHeap(array, n);
A.HeapSort(array, n);
}
foreach (List<int> array in listArrays)
{
foreach (int i in array)
{
Console.WriteLine(string.Join(" ", array));
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:
static void Main(string[] args)
{
Program A = new Program();
string[] array = System.IO.File.ReadAllLines(#"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
int[] arrayInt = Array.ConvertAll(array, int.Parse);
A.BuildHeap(arrayInt, arrayInt.Length);
A.HeapSort(arrayInt, arrayInt.Length);
Console.WriteLine(string.Join(" ", arrayInt));
Console.ReadLine();
}
I need to create 2 methods. Method 1 (CreateArray) shall allow the user to enter the length of an array they would like to create and then enter the value for each element. Method 2 (PrintArray) prints the array created in Method 1.
Both methods work fine on a standalone basis. However, I don't know how to pass CreateArray method to PrintArray method.
class Calculation
{
public int[] CreateArray (int a)
{
int count = 1;
int[] CreateArray = new int[a];
for (int i = 0; i < CreateArray.Length; i++)
{
Console.Write($"{count}.) Enter a value - ");
int userInput = int.Parse(Console.ReadLine());
CreateArray[i] = userInput;
count++;
}
return CreateArray;
}
public void PrintArray(int[] numbers)
{
int elementNum = 1;
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"{elementNum}.) {numbers[i]}");
elementNum++;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the Length of an array you would like to create: ");
int arrayLength = int.Parse(Console.ReadLine());
Calculation calc = new Calculation();
calc.CreateArray(arrayLength);
}
}
You need to store the results of "calc.CreateArray(arrayLength);" in a local variable and pass it to PrintArray():
int[] newArray = calc.CreateArray(arrayLength);
calc.PrintArray(newArray);
I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}
I am trying to ask the user to input 10 numbers. After receiving the numbers, I am storing them in an array followed by printing the array. I came up with the following code to do the task but it is not printing the array.
Also feel that I may have rattled on way too much code for a simple task. Do note that I am very new to c# thus not familiar with advanced stuff or possibly even most of basic stuff. Even the "convert.toInt32", I adopted from reading around and not taught in class yet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_Array
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = Convert.ToInt32(Console.ReadLine());
e = Convert.ToInt32(Console.ReadLine());
f = Convert.ToInt32(Console.ReadLine());
g = Convert.ToInt32(Console.ReadLine());
h = Convert.ToInt32(Console.ReadLine());
i = Convert.ToInt32(Console.ReadLine());
j = Convert.ToInt32(Console.ReadLine());
int[] newArray = {a,b,c,d,e,f,g,h,i,j};
Console.WriteLine(newArray);
Console.ReadLine();
}
}
}
use a for loop.
int[] newArray = new int[10];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
You can use the same loop to display as well:
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
The ToString method of arrays (which is what Console.WriteLine is calling in your code) isn't overloaded to print out the contents of the array. It leaves the basic object implementation of just printing the type name.
You need to manually iterate the array and print out the individual values (or use a method that will do that for you).
I.e.
foreach(var item in array)
Console.WriteLine(item)
or
Console.WriteLine(string.Join("\n", array));
static void Main(string[] args)
{
int[] rollno = new int[10];
Console.WriteLine("Enter the 10 numbers");
for (int s = 0; s < 9; s++)
{
rollno[s] = Convert.ToInt32(Console.ReadLine());
rollno[s] += 110;
}
for (int j = 0; j < 9; j++)
{
Console.WriteLine("The sum of first 10 numbers is : {0}", rollno[j]);
}
Console.ReadLine();
}
}
}
You could simplify things a lot with the following:
static void Main(string[] args)
{
int newArray = new int[10];
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
for (int i = 0; i < 10; i++) {
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The values you've entered are:");
Console.WriteLine(String.Join(", ", newArray));
Console.ReadLine();
}
I have made this code to get from 2a3b to aabbb. This also has to apply when no numbers are given. Like aa2b => aabb.
The program is fully working but my problem is, it takes in alot of space. I think it is my split but my array will be like this if the input is 2a2b:
2
NULL
NULL
a
2
NULL
NULL
b
Does someone know what i'm doing wrong? Is it my split?
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
string[] array = new string[20];
int count = 1;
array = Regex.Split(value, "(\\d{0,2})");
while (count < array.Length)
{
int num;
if (array[count] != "")
{
bool isNumeric = int.TryParse(array[count], out num);
if (!isNumeric)
{
test = test + string.fill(array[count], intNumber);
test = test + array[count];
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
count++;
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
How about using a simple Regex.Replace?
string input = "2a3bcccc";
string output = Regex.Replace(
input,
#"(\d+)(\w)",
m => new String(m.Groups[2].Value[0],int.Parse(m.Groups[1].Value)));
result : aabbbcccc
A simpler way to resolve your problem is to get rid of regex, the array creation would be like:
char[] array = value.ToArray();
The code, with the minor corrections due to the array and some improvements being a char array (intead of a string array):
static void Main(string[] args)
{
string test = "";
int intNumber = 1;
string value = "2a2b";
foreach (char c in value.ToArray())
{
int num;
bool isNumeric = int.TryParse(c.ToString(), out num);
if (!isNumeric)
{
test = test + new string(c, intNumber);
Console.WriteLine(test);
intNumber = 1;
}
else
{
intNumber = num;
}
}
Console.WriteLine("woord:" + test);
Console.ReadLine();
}
Quick test program works like a charm without using a regex.
const string value = "aa2b";
var result = "";
for (var i = 0; i < value.Length; i++)
{
int num;
if (Int32.TryParse(value.Substring(i, 1), out num))
{
for (var j = 0; j < num; j++)
{
result += value.Substring(i + 1, 1);
}
i++;
}
else
{
result += value.Substring(i, 1);
}
}
textBox1.AppendText("woord:" + result);
I generally try to avoid Regex, unless there is a complex pattern I need to verify.
Here is my solution to your problem:
string k = Console.ReadLine();
string t = "";
int count = 0, next;
for (int i = 0; i < k.Length; i++)
{
while (int.TryParse(k[i].ToString(), out next)) // Find the count of the next letter
{
count = count * 10 + next; // If count had a 2, and the next character is 3 (means we need to calculate 23), simply multiply the previous count by 10, and add the new digit
i++; // Move to the next character
}
t += new String(k[i], count > 0 ? count : 1); // Add the new sequence of letters to our string
count = 0; // Clear the current count
}
Console.WriteLine(t);
You can optimize the above, by using the StringBuilder class, but I think it's enough to understand the general solution first, rather than trying to find optimizations.