Ok, I'm attempting to make a simple program that reads in number of pizzas sold for a given day and then have the user input the type of pizza sold for that day (with this I need to use the Split() with the user input).
I'm having issues populating the columns for my jagged array.
Now, I can get what I have to work for only 1 pizza sold, but anything beyond that it is not taking in my user input for the type of pizzas sold for that day (the column values). It's not reading in the user input as separate items so once I input, it goes to the next line like it's waiting for data instead of moving on. (Since I'm testing this for one day, it would end the program once the user input was read in).
I'm not quite sure where my issue is with my loops putting in my column values, but I'm figuring it has something with reading in the user input and placing that in the column of the jagged array. Any help would be great.
static void Main(string[] args)
{
Greeting();
string[][] pizza = new string[7][];
GetPizzas(pizza);
}
static void Greeting()
{
Write("Welcome to Z's Pizza Report!");
}
static void GetPizzas(string[][] array)
{
int numOfPizza;
string day;
for (int r = 0; r < array.Length; r++)
{
if (r == 0)
{
day = "Monday";
Write("How many total pizzas were there for {0}? ", day);
numOfPizza = int.Parse(ReadLine());
while (numOfPizza < 0)
{
Write("Number cannot be negative. Try Again: ");
numOfPizza = int.Parse(ReadLine());
}
array[r] = new string[numOfPizza];
Write("Enter all the pizzas for {0}, seperated by spaces: ", day);
for (int c = 0; c < array[r].Length; c++)
{
string total = ReadLine();
array[c] = total.Split(' ');
while (array[r] != array[c])
{
Write("Input does not match number needed. Try Again: ");
total = ReadLine();
array[c] = total.Split(' ');
}
}
}
else if (r == 1)
{
day = "Tuesday";
}
else if (r == 2)
{
day = "Wednesday";
}
else if (r == 3)
{
day = "Thursday";
}
else if (r == 4)
{
day = "Friday";
}
else if (r == 5)
{
day = "Saturday";
}
else
{
day = "Sunday";
}
}
}
The code seems overly complicated to me, but does something like this help? Oh, notice that I'm using the built-in DayOfWeek enum to parse the friendly name for the day. The difference between this and yours is that Sunday is day 0.
This line of code casts the integer to the enum, and then gets the string value:
var dayOfWeek = ((DayOfWeek)i).ToString();
I also added a helper function to get an integer from the user. It takes in a prompt string, an error string, an optional min value and an optional max value, then it prompts the user for an integer and won't return until they enter a valid value:
static int GetIntFromUser(string prompt, string error,
int minValue = int.MinValue, int maxValue = int.MaxValue)
{
int result;
if (!string.IsNullOrEmpty(prompt)) Console.Write(prompt);
while (!int.TryParse(Console.ReadLine(), out result)
|| result < minValue || result > maxValue)
{
if (!string.IsNullOrEmpty(error)) Console.Write(error);
}
return result;
}
The rest of the code looks like:
static void Main(string[] args)
{
var pizzasSold = new string[7][];
GetPizzas(pizzasSold);
for (int i = 0; i < pizzasSold.Length; i++)
{
var dayOfWeek = ((DayOfWeek)i).ToString();
Console.WriteLine("You sold {0} pizzas on {1}: {2}",
pizzasSold[i].Length, dayOfWeek, string.Join(", ", pizzasSold[i]));
}
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
static void GetPizzas(string[][] array)
{
for (int r = 0; r < array.Length; r++)
{
var dayOfWeek = ((DayOfWeek)r).ToString();
var numPizzasSold =
GetIntFromUser($"How many total pizzas were there for {dayOfWeek}? ",
"Number cannot be negative. Try Again: ", 0);
Console.Write($"Enter all the pizzas for {dayOfWeek}, seperated by spaces: ");
var pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
while (pizzasSold.Length != numPizzasSold)
{
Console.Write($"Input does not match number needed. Try Again: ");
pizzasSold = Console.ReadLine().Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
}
array[r] = pizzasSold;
}
}
using System;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
int[][] n = new int[3][];
int i;
n[0] = new int[4];
n[1] = new int[3];
n[2] = new int[2];
// n[1] = new int[] { 1, 2, 3 };
// Console.WriteLine("enter the rollno");
for (i = 0; i < 4; i++)
{
n[0][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 3; i++)
{
n[1][i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < 2; i++)
{
n[2][i] = Convert.ToInt32(Console.ReadLine());
}
// for (i = 0; i < 3; i++)
// {
// n[i][j] = Convert.ToInt32(Console.ReadLine());
//}
for (i = 0; i <4; i++)
{
Console.Write(n[0][i] + " ");
}
Console.WriteLine();
for (i = 0; i < 3; i++)
{
Console.Write(n[1][i] + " ");
}
}
}
}
Related
using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}
I wanted this program to print out random numbers (1-6) in Columns forever until all the rows of each columns have the exact same number. If the user enters 5 forexample, it will print out 5 columns of random numbers (1-6) until each row of that 5 columns are the same . I am stuck, I don't know how to check all the elements of the array, whether or not they are all the same with one another.
namespace Dice_Roll_2._0
{
class Program
{
static void Main(string[] args)
{
int userinput = Convert.ToInt16(Console.ReadLine());
Random Dice = new Random();
bool search = true;
while (search)
{
var output = string.Empty;
int[] numberofdice = new int[userinput+1];
for (int i = 1; i <=userinput; i++)
{
numberofdice[i] = Dice.Next(1, 7);
output += numberofdice[i];
if (i < userinput )
{
output += "\0";
}
if (numberofdice[i-1] == numberofdice[i])
{
search = false;
}
}
Console.WriteLine(output);
}
Console.ReadLine();
}
}
}
With the Linq namespace, you can do a Distinct() on your array of columns and when the Count() of the Distinct() equals 1, then all the columns are the same and you can stop rolling.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write("Enter number of columns: ");
int userinput = Convert.ToInt16(Console.ReadLine());
int[] columns = new int[userinput];
Random Dice = new Random();
bool search = true;
DateTime start = DateTime.Now;
while (search)
{
for (int i = 0; i < columns.Length; i++)
{
columns[i] = Dice.Next(1, 7);
}
if (columns.Distinct().Count() == 1)
{
Console.WriteLine("All columns match with the value of {0}", columns[0]);
Console.WriteLine("It took {0} to get all columns to match", DateTime.Now.Subtract(start));
search = false;
}
}
}
}
Results (Time span and value will vary on each run):
Enter number of columns: 5
All columns match with the value of 4
It took 00:00:00.0156260 to get all columns to match
Fiddle Demo is limited to 7 columns.
Array indexing should begin with 0. To check that all elements are the same, you can use a loop to compare each element with the first.
static void Main(string[] args)
{
int userinput = Convert.ToInt16(Console.ReadLine());
Random Dice = new Random();
int[] numberofdice = new int[userinput + 1];
while(true)
{
var output = string.Empty;
// Generate the userinput random numbers
// as well as output string
for(int i = 0; i < userinput; i++)
{
numberofdice[i] = Dice.Next(1, 7);
output += numberofdice[i];
}
Console.WriteLine(output);
// Check that they are all same by comparing with first
bool same = true;
int first = numberofdice[0];
for(int i = 1; i < userinput; i++)
{
if(numberofdice[i] != first)
{
same = false;
break;
}
}
// If all were the same, stop.
if(same)
break;
}
}
Hi guys so i'm starting to learn C# and I came up with this problem when I was trying to mix things up
It says "Input string was not in correct format" at the
n = Convert.ToInt32(Console.ReadLine());
Here's the whole code
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
Use Integer.TryParse to handle the strings potentially not being numbers. Then prompt the user if the input is not parsable to enter valid input.
Convert and Parse both will throw exceptions if the string is not an exact number.
https://msdn.microsoft.com/en-us/library/f02979c7%28v=vs.110%29.aspx
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}
since im new to C#, even though i have coded in C before, i still have a question on how I go about to execute the part where i ask the user to enter a set of inputs after a program has already been run.
The following program prints a calendar with the specified number of months, but i need help writing another line of code that would ask the user to enter the month, year and number of months to be printed, after the user has already inputed the values once. Do i have to do some type of looping in my main function or do i have to do it on the method above my main function ?
static void GenMonth(int month, int year)
{
int daycode, ndim;
PrintHeader(month, year);
ndim=GetNDIM(month,year);
int day=1;
daycode = GetDayCode(month, day, year);
int a,i;
for(a=1;a<=daycode;a++)
{
Console.Write(" ");
}
for (i = 1; i <= GetNDIM(month, year); i++)
{
Console.Write("{0,4}", i);
if (((i + daycode) % 7) == 0)
Console.Write("\n");
}
daycode = GetDayCode(month, day, year);
if (daycode == 6)
{
Console.Write("\n");
}
}
static void Main(string[] args)
{
Console.WriteLine("please enter m,y,n: \n");
string input = Console.ReadLine();
string[] split = input.Split(' ');
int month = Int32.Parse(split[0]);
int year = Int32.Parse(split[1]);
int numberOfMonths = Int32.Parse(split[2]);
int i=0;
for (i = 0; i < numberOfMonths; i++)
{
GenMonth(month, year);
month++;
Console.Write("\n \n");
}
if (month > 12)
{
month = 1;
year++;
}
Console.ReadKey();
}
You'll probably get a few ways to do this - here's one possibility. Just loop continuously, then break out of the loop (and the program will terminate) when you detect a value of 0 for the month.
static void Main(string[] args)
{
int month = -1;
while (true)
{
Console.WriteLine("please enter m,y,n: \n");
string input = Console.ReadLine();
string[] split = input.Split(' ');
month = Int32.Parse(split[0]);
if (month == 0)
break;
int year = Int32.Parse(split[1]);
int numberOfMonths = Int32.Parse(split[2]);
...
...
}
}
Try this out:
static void Main(string[] args)
{
while (AskForDate())
{}
}
private static bool AskForDate()
{
Console.WriteLine("please enter m,y,n: \n");
string input = Console.ReadLine();
string[] split = input.Split(' ');
int month = Int32.Parse(split[0]);
int year = Int32.Parse(split[1]);
int numberOfMonths = Int32.Parse(split[2]);
int i = 0;
for (i = 0; i < numberOfMonths; i++)
{
GenMonth(month, year);
month++;
Console.Write("\n \n");
}
if (month > 12)
{
month = 1;
year++;
}
Console.Out.WriteLine("Again? [Y/n]");
var key = Console.ReadKey();
return key.Key != ConsoleKey.N;
}
for(;;)
{
Console.WriteLine("Enter: Month Year NumberOfMonths\nPress enter to stop.");
string line = Console.ReadLine();
if (line == "")
break;
string[] terms = line.Split();
int
month = int.Parse(terms[0]),
year = int.Parse(terms[1]),
numberOfMonths = int.Parse(terms[2]);
for (int i = 0; i < numberOfMonths; i++)
{
GenMonth(month, year);
if (month == 12)
{
month = 1;
year++;
}
else
month++;
}
}
Console.Write("\nPress any key...");
Console.ReadKey();
Just use a while clause:
static void Main(string[] args)
{
Console.WriteLine("please enter m,y,n: \n");
string input = Console.ReadLine();
string[] split = input.Split(' ');
int month = Int32.Parse(split[0]);
while (month != 0)
{
int year = Int32.Parse(split[1]);
int numberOfMonths = Int32.Parse(split[2]);
int i=0;
for (i = 0; i < numberOfMonths; i++)
{
GenMonth(month, year);
month++;
Console.Write("\n \n");
}
if (month > 12)
{
month = 1;
year++;
}
Console.ReadKey();
Console.WriteLine("please enter m,y,n: \n");
input = Console.ReadLine();
split = input.Split(' ');
month = Int32.Parse(split[0]);
}
}
Let me know if that's not what you meant.
I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}