How to assing value to tab by variable c# - c#

I'm trying to make program to sort tabs but I can't make working table. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SorotwanieTablic
{
class Program
{
static int NumberOfObjectInTab;
static void Numb(int NumberOfObjectInTab)
{
do
{
Console.WriteLine("Wprowadź liczbę elementów do posortowania <1 .. 10>: ");
Program.NumberOfObjectInTab = int.Parse(Console.ReadLine());
}
while (NumberOfObjectInTab < 0 || NumberOfObjectInTab > 10);
}
static int[] tab = new int[NumberOfObjectInTab];
static void InsertValuesToTab(int[] tab)
{
for (int i=0; i < tab.Length; i++)
{
Console.WriteLine("Wprowadź liczbę [{0}] ", i);
tab[i] = int.Parse(Console.ReadLine());
}
}
static void Main(string[] args)
{
Numb(NumberOfObjectInTab);
InsertValuesToTab(tab);
Console.WriteLine("\nprzed sortowaniem ");
foreach (int i in tab) Console.Write(+i + " ");
Array.Sort(tab);
Console.WriteLine("\nPO Posortowaniu ");
foreach (int i in tab) Console.Write( + i + " ");
Console.Read();
}
}
}
How user can enter the size of tab from keyboard?
I dunno what to do. I tried return NumberOfObjectInTab but nothing changes. With void and with int there is still same value to tab.
It sort if I change to static int[] tab = new int[5]; (for example) but... I must have size of tab defined by user, not by code.

Break your application down into the functions it needs to perform the desired work. Maybe start with non-implementation first. The create the implementations.
static int sizeOfTab;
static int[] tab;
static void Main(string[] args)
{
CollectSizeOfTab(args);
CreateTab();
InsertValuesToTab(tab);
Sort(tab);
}
static void CollectSizeOfTab(string[] args)
{
do
{
Console.WriteLine("Wprowadź liczbę elementów do posortowania <1 .. 10>: ");
sizeOfTab = int.Parse(Console.ReadLine());
}while (sizeOfTab < 0 || sizeOfTab > 10);
}
static void CreateTab(){tab = new int[sizeOfTab];}
static void InsertValuesToTab(int[] tab){...}
static void Sort(int[] tab){...}
How user can enter the size of tab from keyboard?
Console.Write("Enter size of tab:");
var response = Console.ReadLine();

Related

Input any mathematical table without using loops

I need to print mathematical table without using any loop (for, while, do while, etc.). Can anyone help me out, the easiest example I could find was writing console.writeline 10times for each line.
This is my code!
using System;
using System.Linq;
class Question4
{
int product, i=1;
public static void Main(string[] args)
{
int num;
Console.Write("Enter the Number to Print its Multiplication Table: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nMultiplication Table For {0}: ",num);
TableFunctionName (num);
}
public void TableFunctionName(int n)
{
if(i<=10)
{
table=n*i;
Console.WriteLine("{0} x {1} = {2}",n,i,table);
i++;
}
return;
}
}
Using recursion
static void Multiply(int a, int b) {
if (a > 1)
Multiply(a - 1, b);
Console.WriteLine($"{a} * { b} = {a * b}");
}
static void Main(string[] args) {
Multiply(10, 5);
}
}
You could use recursion
public static void Main()
{
Console.Write("Enter the Number to Print its Multiplication Table: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
CalculateAndPrint(number, 1);
}
static void CalculateAndPrint(int number, int factor)
{
if (factor > 9) return;
Console.WriteLine("{0} x {1} = {2}", number, factor, number * factor);
CalculateAndPrint(number, ++factor);
}

How to make my program say that I'm close or far from the answer and then to input it again? C#

Here I have the program that selects random number for me to guess. How can I make it now to say that number is close or far away from original random selected by the program?
using System;
namespace higherlower_guesser
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int randomNumber = rnd.Next(0, 100);
bool answerCheck = false;
int guessAttempts = 0;
while (answerCheck == false)
{
Console.Clear();
Console.WriteLine("Take a guess.");
guessAttempts++;
int enteredValue = int.Parse(Console.ReadLine());
if (enteredValue == randomNumber)
{
Console.WriteLine("Congratulations, the number in mind is {0}. You've had {1} attempts", randomNumber, guessAttempts);
answerCheck = true;
}
}
}
}
}
You need to define what "close" and "far" are for your app. You can do something like:
const int CloseRange = 10;
if (enteredValue <= CloseRange) { /* we are close! */ }
else { /* we are far! */ }

How to ignore "Enter" key press in C# Console Application?

using System;
using System.Text;
namespace 判断输入是否为数字
{
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
char temp = Console.ReadKey().KeyChar;
if (char.IsDigit(temp))
{
news[i] = temp;
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
}
This ConsoleApp is suppose to input year、month、day from Console. I want to disable key except digital numbers(0-9).
Now this is my code, generally, it works.
But, for example, I want to input "2020" to year, when I input "202" and press Enter, the cursor will jump to the beginning of this line. It looks like the screenshot, Although it will not affect the final result.
I want to Console ignore the Enter key press(nothing happen), How to do that please?
My Sceenshot
This is how you can skip the enter key
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
var key = Console.ReadKey();
if (key.KeyChar.IsDigit(temp))
{
news[i] = temp;
}
else if(key == ConsoleKey.Enter)
{
// ignore
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}

No errors in Visual Studio, Code Executes but something not right C# (updated! problem in String.Insert)

I'm writing a program for schoolwork, that's supposed to generate a 10 000 "movie" list. A single "movie" consist of a string in a form "moviename year director". I say "movie" because movie name and director are supposed to be randomly generated with letters from a-z.
I wrote the following logic to generate one such "movie". Movie name and director are random letter combination in length between 4-10 charachters. Code gives no errors in visual studio, executes, but shows blank. If I wrote correctly, then this code should generate one such string and print it, yet console is blank.
Do while loop is there to check if, however unlikely, there is a double item in the List (this is for when I do the 10 000 version).
In short, I dont understand what am I doing wrong?
using System;
using System.Collections.Generic;
using System.Linq;
namespace Experiment
{
class Program
{
static void Main(string[] args)
{
Movies();
Console.ReadKey();
}
public static void Movies()
{
List<string> movieList = new List<string>();
bool check = false;
do
{
string movie = "";
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
movie.Insert(0, " ");
movie.Insert(0, Convert.ToString(GetYear()));
movie.Insert(0, " ");
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
if (movieList.Contains(movie))
{
check = false;
}
else
{
movieList.Add(movie);
check = true;
}
} while (check == false);
Console.WriteLine(movieList[0]);
}
public static Random _random = new Random();
public static char GetLetter()
{
int num = _random.Next(0, 26);
char let = (char)('a' + num);
return let;
}
public static int GetNum()
{
int num = _random.Next(4, 11);
return num;
}
public static int GetYear()
{
int num = _random.Next(1920, 2020);
return num;
}
}
}
Strings are immutable, so calling the Insert() method on the movie string doesn't do anything to the current movie variable. Instead it returns the new string.
You are however better off changing the movie type from string to StringBuilder, which is a dynamically allocated buffer of characters, so your example becomes:
using System;
using System.Text;
using System.Collections.Generic;
namespace sotest
{
class Program
{
static void Main(string[] args)
{
Movies();
Console.ReadKey();
}
public static void Movies()
{
List<string> movieList = new List<string>();
bool check = false;
do
{
StringBuilder movie = new StringBuilder();
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
movie.Insert(0, " ");
movie.Insert(0, Convert.ToString(GetYear()));
movie.Insert(0, " ");
for (int i = 0; i < GetNum(); i++)
{
movie.Insert(0, Convert.ToString(GetLetter()));
}
if (movieList.Contains(movie.ToString()))
{
check = false;
}
else
{
movieList.Add(movie.ToString());
check = true;
}
} while (check == false);
Console.WriteLine(movieList[0]);
}
public static Random _random = new Random();
public static char GetLetter()
{
int num = _random.Next(0, 26);
char let = (char)('a' + num);
return let;
}
public static int GetNum()
{
int num = _random.Next(4, 11);
return num;
}
public static int GetYear()
{
int num = _random.Next(1920, 2020);
return num;
}
}
}
The problem is that you are using movie.Insert incorrectly.
If you read the documentation for String.Insert it says
https://learn.microsoft.com/en-us/dotnet/api/system.string.insert?view=netframework-4.8
Returns a new string in which a specified string is inserted at a
specified index position in this instance
public string Insert (int startIndex, string value);
So it returns a new String, it does not amend the existing one. So you would need to do.
movie = movie.Insert(0, Convert.ToString(GetYear()));
However, I must also say that using String.Insert in this way is not the best approach.
You should instead look at using the StringBuilder class. It is very efficient when you want to amend strings (which are immutable objects).
You might want to read parts of this to help you understand. If you scroll down then it also suggests StringBuilder.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/
Insert() method is used to return a new string from the specified string at a specified index position. In your case, you are not capturing the updated string.
The best approach to solve this is through using StringBuilder object. Please note that StringBuilder object is much efficient rather than playing with immutable string.

c# parallel arrays data from text file

Here's the problem: Index was outside the bounds of the array. Assignment: Write a program that determines the number of students who can still enroll in a given class. Design your solution using parallel arrays. Test your solution by retrieving the following data from a text file. Define a exception class for this problem if the current enrollment exceeds the maximum enrollment by more than three. Halt the program and display a message indicating which course is over-enrolled.
Here's the original code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private static string[] classes = { "CS150", "CS250", "CS270", "CS300", "CS350" };
private static int[] currentEnrolled = { 18, 11, 9, 4, 20 };
private static int[] maxEnrollment = { 20, 20, 20, 20, 20 };
private static int currentEnrollment()
{
int enrolled = 0;
foreach (int i in currentEnrolled)
{
enrolled += i;
}
return enrolled;
}
private static void listClasses()
{
foreach (string i in classes)
{
Console.WriteLine("Class: {0}", i);
}
}
private static void ClassStatus()
{
for (int i = 0; i < currentEnrolled.Length; i++)
{
Console.WriteLine("Class: {0}, Max: {1}, Current: {2}, remaining: {3}", classes[i], maxEnrollment[i], currentEnrolled[i], maxEnrollment[i] - currentEnrolled[i]);
}
}
static void Main(string[] args)
{
Console.WriteLine("Currently Enrolled: {0}", currentEnrollment());
ClassStatus();
Console.ReadKey(false);
}
}
}
Now, I've been editing the above code to take a text file instead, however I get an error. Here's what I'm working with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
private static string[] classes = new string[900];
private static int[] currentEnrolled = new int[900];
private static int[] maxEnrollment = new int[900];
private static int currentEnrollment()
{
int enrolled = 0;
foreach (int i in currentEnrolled)
{
enrolled += i;
}
return enrolled;
}
private static void listClasses()
{
foreach (string i in classes)
{
Console.WriteLine("Class: {0}", i);
}
}
private static void ClassStatus()
{
for (int i = 0; i < currentEnrolled.Length; i++)
{
Console.WriteLine("Class: {0}, Max: {1}, Current: {2}, remaining: {3}", classes[i], maxEnrollment[i], currentEnrolled[i], maxEnrollment[i] - currentEnrolled[i]);
}
}
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("classes.txt");
int i = 0;
foreach (string line in File.ReadAllLines("classes.txt"))
{
string[] parts = line.Split(',');
while (i < 900 && i < parts.Length)
{
classes[i] = parts[1];
currentEnrolled[i] = int.Parse(parts[2]);
maxEnrollment[i] = int.Parse(parts[3]);
}
i++;
}
Console.WriteLine("Currently Enrolled: {0}", currentEnrollment());
ClassStatus();
Console.ReadKey(false);
}
}
}
Some of the components used in the above code were taken from this article: Splitting data from a text file into parallel arrays
Text file looks like this:
CS150,18,20
CS250,11,20
CS270,32,25
CS300,4,20
CS350,20,20
Any assistance will be appreciated. And yes, this is an assignment. Programming is most definitely not my strong suit.
There seem to be multiple problems with your while loop.
First, parts.Length will always be 3, since you have 2 commas and split on that. So the condition i < 900 && i < parts.Length does not really make sense, it's like i < 900 and i < 3, so it will always stop at 3. The intent is not really clear here, I think you meant to loop on each 900 values, but fi soforeach already does that for you.
Next, since there's 3 parts and C# arrays are 0-based, it should be parts[0], parts[1] and parts[2]. That's what causing your 'out of range' exception.
Finally, i++; should be in your while loop. If you leave it outside, you will loop forever as the index will never increase.
Basically, it should be something like this :
while (i < 900)
{
classes[i] = parts[0];
currentEnrolled[i] = int.Parse(parts[1]);
maxEnrollment[i] = int.Parse(parts[2]);
i++;
}
Again, the 900 is not really clear since you don't have 900 values per line (remember you're in a foreach). In my opinion you might as well scratch all that and redo it carefully.
What you need to do, is the following :
Read the file and store all the lines
Foreach line do:
Split the line in 3 parts
Store each separate part
Write results
For the "custom exception" part, you can add:
For the length of currentEnrollment do:
If currentEnrollment at current index is superior than maxEnrollment at current index do:
Throw a new exception with the className at current index

Categories

Resources