I got stuck with a small problem. I create a program where the user must to choose 5 options( 1.input numbers 2. Show smallest 3. Show Greatest 4. Display all numbers 5 Quit.)
All the option are working. The problem is that when the user is choosing the option, if the press any letters is giving me error. I want that if the user is pressing any letter ori any symbol to be a warning message like "Unknown option value entered" and to try again. I suppose is about conversion or something similar, but i can't find where is the problem.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignmen2014_15
{
class Program
{
const int MAXNUMBERS = 3;
static void Main(string[] args)
{
int[] theNumbers = new int[MAXNUMBERS];
int chosenOption = 0;
bool quit = false;
InitialiseNumbers(theNumbers);
while (quit == false)
{
DisplayHeader();
DisplayMenu();
chosenOption = ReadNumber("Please choose an option: ");
quit = ProcessMenu(chosenOption, theNumbers);
Console.Clear();
}
}
static void InitialiseNumbers(int[] numbers)
{
for (int index = 0; index < MAXNUMBERS; index++)
{
numbers[index] = 0;
}
}
static void DisplayHeader()
{
WriteText("*******************************************************************************", 0, 0); // Top left hand corner of screen is x = 0, y = 0;
WriteText("* This application is designed to allow you to choose numbers *", 0, 1); // Next line down is x = 0, y = 1, etc WriteText("* and finds the biggest and the smallest value *", 0, 2);
WriteText("*******************************************************************************", 0, 3);
}
static void DisplayMenu()
{
WriteText("Select an option", 20, 8); // Display menu at at x = 20, y = 8
WriteText("1. Enter the numbers", 20, 9);
WriteText("2. Find the smallest", 20, 10);
WriteText("3. Find the largest", 20, 11);
WriteText("4. Display all numbers", 20, 12);
WriteText("5. Quit", 20, 13);
}
static void WriteText(string text, int x, int y)
{
Console.CursorLeft = x;
Console.CursorTop = y;
Console.Write(text);
}
static int ReadNumber(string prompt)
{
string text;
int number;
WriteText(prompt, 20, 14);
text = Console.ReadLine();
number = int.Parse(text);
ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
return number;
}
static void ClearText(int x, int y, int length)
{
// Write space ' ' characters starting at x, y for 'length' times
WriteText(new String(' ', length), x, y);
}
static void DisplayNumbers(int[] theNumbers)
{
Console.Write("Your numbers are: ");
for (int i = 0; i < MAXNUMBERS; i++)
{
Console.WriteLine(theNumbers[i]);
}
}
static bool ProcessMenu(int option, int[] numbers)
{
bool quit = false;
switch (option)
{
case 1:
GetNumbers(numbers);
break;
case 2:
WriteText(string.Format("The smallest value is {0}", FindSmallest(numbers)), 20, 15);
Console.ReadKey(); // Pause
break;
case 3:
WriteText(string.Format("The largest value is {0}", FindLargest(numbers)), 20, 15);
Console.ReadKey(); // Pause
break;
case 4:
DisplayNumbers(numbers);
Console.ReadKey();
break;
case 5:
quit = IsQuitting();
break;
default:
WriteText("Unknown option value entered", 20, 15);
Console.ReadKey(); // Pause
break;
}
return quit;
}
static void GetNumbers(int[] numbers)
{
for (int index = 0; index < MAXNUMBERS; index++)
{
numbers[index] = ReadNumber("Enter number: ");
}
}
static int FindSmallest(int[] numbers)
{
int smallest = numbers[0];
for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
{
if (numbers[index + 1] < smallest)
{
smallest = numbers[index + 1];
}
}
return smallest;
}
static int FindLargest(int[] numbers)
{
int largest = numbers[0];
for (int index = 0; index < MAXNUMBERS - 1; index++) // <-- subtract 1
{
if (numbers[index + 1] > largest)
{
largest = numbers[index + 1];
}
}
return largest;
}
static bool IsQuitting()
{
string response;
bool quit = false;
WriteText("Do you really wish to quit? ", 20, 13);
response = Console.ReadLine();
if (response.Equals("Yes" , StringComparison.InvariantCultureIgnoreCase) || response.Equals("Y", StringComparison.InvariantCultureIgnoreCase))
{
quit = true;
}
return quit;
}
}
}
Use Int32.TryParse(String, Int32) method which tries to parse string into integer and returns boolean value representing if parsing was successful or not. In your case, if parsing fails, you can return -1 from your ReadNumber method which will call default: part of your switch case and an error message will be displayed. Otherwise, if parsing was successful, you can simply return the parsed number, which will be either be one of your desired numbers or it will call default: action.
The following is example from Microsoft documentation
String[] values = { null, "160519", "9432.0", "16,667",
" -322 ", "+4302", "(100);", "01FA" };
foreach (var value in values)
{
int number;
bool success = Int32.TryParse(value, out number);
if (success)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
value ?? "<null>");
}
}
In your specific example you need to modify your ReadNumber(string prompt) method:
static int ReadNumber(string prompt)
{
string text;
int number;
WriteText(prompt, 20, 14);
text = Console.ReadLine();
bool is_parsing_successful = Int32.TryParse(text, out number);
ClearText(20, 14, prompt.Length + text.Length); // Clear the text at this line
if(is_parsing_successful){
return number;
} else {
return -1;
}
}
Related
I'm creating this Blackjack game and I'm having trouble calculating the total value of both the dealer and player. I've created a method to calculate the value for both the player(PlayerTotalCalculate) and the dealer (DealerTotalCalculate) using forloops.
When I run the program, the first sequence of cards are added up correctly, but when I "HIT" to get a new card for the player, it takes the previous value shown and adds the new card given as well as the value of the 2 cards given previously..
using System;
using System.Collections.Generic;
namespace BlackJack2
{
internal class Program
{
//GLOBAL VARIABLES
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
enum Phase { StartGame, DealersFirst, PlayersTurn, DealersTurn, ChooseWinner, End }
static Phase currentPhase;
static int userInput;
static void Main(string[] args)
{
string suitFace = "";
int dealersTotalValue = 0;
int playersTotalvalue = 0;
//Creating the list of cards
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
suitFace = "Diamonds";
break;
case 1:
suitFace = "Spades";
break;
case 2:
suitFace = "Hearts";
break;
case 3:
suitFace = "Clubs";
break;
}
myListOfCards.Add(new Card("King", suitFace, 10));
myListOfCards.Add(new Card("Queen", suitFace, 10));
myListOfCards.Add(new Card("Jack", suitFace, 10));
myListOfCards.Add(new Card("10", suitFace, 10));
myListOfCards.Add(new Card("9", suitFace, 9));
myListOfCards.Add(new Card("8", suitFace, 8));
myListOfCards.Add(new Card("7", suitFace, 7));
myListOfCards.Add(new Card("6", suitFace, 6));
myListOfCards.Add(new Card("5", suitFace, 5));
myListOfCards.Add(new Card("4", suitFace, 4));
myListOfCards.Add(new Card("3", suitFace, 3));
myListOfCards.Add(new Card("2", suitFace, 2));
myListOfCards.Add(new Card("Ace", suitFace, 1));
}
for (int i = 0; i < playersHand.Count; i++)
{
playersHand.Remove(playersHand[i]);
}
for (int i = 0; i < dealersHand.Count; i++)
{
dealersHand.Remove(dealersHand[i]);
}
//Assigning the first phase
currentPhase = Phase.DealersFirst;
DealersTurn(dealersTotalValue, playersTotalvalue);
}
//Deal Card Method using Random Number Generator
static void DealCard(int dealerTotalValue, int playersTotalValue)
{
Random r = new Random();
int randomNumber = r.Next(0, myListOfCards.Count);
if (currentPhase == Phase.DealersFirst || currentPhase == Phase.DealersTurn)
{
dealersHand.Add(myListOfCards[randomNumber]);
}
else if (currentPhase == Phase.PlayersTurn)
{
playersHand.Add(myListOfCards[randomNumber]);
//PlayerTotalCalulate(ref playersTotalValue);
}
myListOfCards.RemoveAt(randomNumber);
}
//Determining dealer's actions
static void DealersTurn(int dealersTotalvalue, int playersTotalValue)
{
if (currentPhase == Phase.DealersFirst)
{
for (int i = 0; i < 1; i++)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
}
DisplayDealerCards();
Console.WriteLine($"The dealer has a total value of: {dealersTotalvalue}");
currentPhase = Phase.PlayersTurn;
PlayersTurn(dealersTotalvalue, playersTotalValue);
}
else if (currentPhase == Phase.DealersTurn)
{
while (dealersTotalvalue < 15)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
DisplayDealerCards();
Console.WriteLine($"The dealer's new total is: {dealersTotalvalue}");
}
CalculateWinner(dealersTotalvalue, playersTotalValue);
}
}
static void PlayersTurn(int dealersTotalValue, int playersTotalValue)
{
for (int i = 0; i < 2; i++)
{
DealCard(dealersTotalValue, playersTotalValue);
}
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You have a total value of: {playersTotalValue}");
while (currentPhase == Phase.PlayersTurn)
{
Console.WriteLine("Would you like to hit or stay?");
Console.WriteLine("1: HIT or 2: STAY");
int.TryParse(Console.ReadLine(), out userInput);
if (userInput == 1)
{
DealCard(dealersTotalValue, playersTotalValue);
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You now have a total value of: {playersTotalValue}");
}
else if (userInput == 2)
{
currentPhase = Phase.DealersTurn;
DealersTurn(dealersTotalValue, playersTotalValue);
}
else
{
Console.WriteLine("Invalid input! Please try again.");
}
}
}
static void DisplayPlayerCards(int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
Console.WriteLine($"You were dealt a(n): {playersHand[i].DisplayCard()}");
}
PlayerTotalCalulate(ref playersTotalValue);
}
static void DisplayDealerCards()
{
//Showing only one card from the dealer
for (int i = 0; i < dealersHand.Count; i++)
{
Console.WriteLine($"The dealer is showing: {dealersHand[i].DisplayCard()}. The other card is hidden.");
}
}
static void CalculateWinner(int dealersTotalvalue, int playersTotalValue)
{
if (playersTotalValue > dealersTotalvalue && playersTotalValue < 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Great job! You've won!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue == dealersTotalvalue)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("The game is a tie!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue < dealersTotalvalue && playersTotalValue > 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Oh no! You've lost!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
//Console.WriteLine(PlayerTotalCalulate(ref playersTotalValue));
}
static void PlayerTotalCalulate(ref int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
playersTotalValue += playersHand[i].Value;
}
}
static void DealerTotalCalculate(ref int dealersTotalValue)
{
for (int i = 0; i < dealersHand.Count; i++)
{
dealersTotalValue += dealersHand[i].Value;
}
}
static void DisplayAllCards()
{
for (int i = 0; i < myListOfCards.Count; i++)
{
Console.WriteLine(myListOfCards[i].DisplayCard());
Console.WriteLine("\n\r\t");
}
}
static void DisplayingSingleCard()
{
Console.WriteLine(myListOfCards[0].DisplayCard());
}
}
}
I've also provided a screenshot of the console itself.
ConsolePicture
In DealerTotalCalculate, you should set dealersTotalValue to 0 before you add up the cards.
You need to do that in PlayerTotalCalulate as well.
As said in my comment, it's because your total variable is never reseted. So when you call the method to add the new value, it takes also the old value into consideration. So you just need to do total = 0, before calling the compute method.
Also consider this to simplify your compute method :
int[] array = { 1, 2, 3, 4, 5 };
int sum = array.Sum();
Console.WriteLine(sum);
It's slightly better, regarding code readability in my opinion. Not a big deal at all.
This question already has an answer here:
How can i check the winner in the my Connect four java code? [closed]
(1 answer)
Closed 4 years ago.
I got an assignment to program connect-4 in console. I have already programmed the board, but I am having a very hard time calculating the winner.
This is what I got so far:
// Array play board
int[,] intRaster = new int[6,7];
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
Label_0:
Console.Write(" \n\n\t\t\t Speler 1: Maak uw zet!");
// Player 1
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("1");
Console.SetCursorPosition(60, 13);
}
// Gives error message if player tries to put a disk in a
// full colom
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_0;
}
// Player 2
Label_1:
Console.Write(" \n\n\t\t\t Speler 2: Maak uw zet!");
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("2");
Console.SetCursorPosition(60, 13);
}
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_1;
}
goto Label_0;
So what I basicly did was declaring a 2 dimensional integer array [6,7].
The for loop will display the gameboard with the values of the array (which at the start would be 0 for every value).
Then the switch will read de character input of the player. If player 1 presses 1 the value 0 ([6, 0]) will be replaced by 1 etc...
Of course the switch contains more cases, but I left those out to shorten this code. So how do I calculate the winner horizontal, vertical and diagonally?
Any help will be much appreciated!
Here you are, I got overexcited.. :-)
class Game
{
static int[,] intRaster = new int[6, 7];
static int[] positionsDiskCount = new int[7];
public static void Main()
{
// Array play board
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
while (true)
{
MakeMove(1);
MakeMove(2);
}
}
static private int MakeMove(int Player)
{
Console.Write(" \n\n\t\t\t Speler {0}: Maak uw zet! ", Player);
int num = -1;
bool moveMade = false;
while (!moveMade)
{
while (true)
{
string key = Console.ReadKey(true).KeyChar.ToString();
if (key == "\u001b") Environment.Exit(0);
if (int.TryParse(key, out num) && num > -1 && num < 8) break;
}
num--;
if (positionsDiskCount[num] < 6)
{
intRaster[num, positionsDiskCount[num]] = Player;
Console.SetCursorPosition(32 + num * 2, 9 - positionsDiskCount[num]);
Console.Write(Player);
Console.SetCursorPosition(60, 10);
bool win = CheckWinner(num, positionsDiskCount[num]);
if (win)
{
Console.WriteLine(" \n\n\t\t\t Speler {0} has won the game!!!!!!", Player);
Console.WriteLine("Press any key to exit");
Console.ReadKey(true).KeyChar.ToString();
Environment.Exit(0);
}
positionsDiskCount[num]++;
moveMade = true;
}
else
{
Console.SetCursorPosition(60, 10);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!! Maak uw zet!");
Console.ReadKey();
Console.SetCursorPosition(60, 10);
}
}
return num;
}
static public bool CheckWinner(int x, int y)
{
//Horizontal
int count = countDirection(x, y, -1, 0);
count += countDirection(x, y, 1, 0);
if (count > 2) return true;
count = countDirection(x, y, 0, -1);
count += countDirection(x, y, 0, 1);
if (count > 2) return true;
count = countDirection(x, y, -1, -1);
count += countDirection(x, y, 1, 1);
if (count > 2) return true;
count = countDirection(x, y, 1, -1);
count += countDirection(x, y, -1, 1);
if (count > 2) return true;
return false;
}
static public int countDirection(int x, int y, int stepX, int stepY)
{
int count = 0;
int Player = intRaster[x, y];
x += stepX;
y += stepY;
while (x >= 0 && x < intRaster.GetUpperBound(1) && y >= 0 && y < intRaster.GetUpperBound(0))
{
if (Player == intRaster[x, y]) count++;
else break;
x += stepX;
y += stepY;
}
return count;
}
}
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] + " ");
}
}
}
}
I am playing around with sorting arrays and I figured out how to MergeSort an int array. But I cant figure out to MergeSort a string array. Sorting string array is easy enough when normal sorting but Merge Sort is different. The code I have done so far is below and is working on int arrays.
public int number = 1;
public void mergeSort(int[] sortArray, int lower, int upper)
{
int middle;
if (upper == lower)
return;
else
{
middle = (lower + upper) / 2;
mergeSort(sortArray, lower, middle);
mergeSort(sortArray, middle + 1, upper);
Merge(sortArray, lower, middle + 1, upper);
}
}
public void Merge(int[] sortArray, int lower, int middle, int upper)
{
string[] temp = new string[sortArray.Length];
int lowEnd = middle - 1;
int low = lower;
int n = upper - lower + 1;
while ((lower <= lowEnd) && (middle <= upper))
{
if (sortArray[lower] <= sortArray[middle])
{
temp[low] = sortArray[lower].ToString();
low++;
lower++;
}
else
{
temp[low] = sortArray[middle].ToString();
low++;
middle++;
}
}
while (lower <= lowEnd)
{
temp[low] = sortArray[lower].ToString();
low++;
lower++;
}
while (middle <= upper)
{
temp[low] = sortArray[middle].ToString();
low++;
middle++;
}
for (int i = 0; i < n; i++)
{
sortArray[upper] = Int32.Parse(temp[upper]);
upper--;
}
}
private void btnExecute_Click(object sender, EventArgs e)
{
String arraylength;
int num;
arraylength = Microsoft.VisualBasic.Interaction.InputBox("Enter a number to determine the length of the array", "Enter Number");
try
{
while (!(int.TryParse(arraylength, out num)))
{
MessageBox.Show("Not a valid number, try again.");
arraylength = Microsoft.VisualBasic.Interaction.InputBox("Enter a number a to determine the length of the array", "Enter Number");
}
}
catch (Exception ex)
{
MessageBox.Show("Value entered is not in a valid format");
}
int intlength = Int32.Parse(arraylength);
string[] stringsArray = new string[intlength];
int arraypos = 0;
// For display purposes
int positionvalue = 1;
txtOutput.Text += "Unsorted array: \r\n";
foreach (string s in stringsArray)
{
string arrayvalue = Microsoft.VisualBasic.Interaction.InputBox("Enter a number for array value" + positionvalue, "Enter Number");
string arrayvalues = arrayvalue;
stringsArray[arraypos] = arrayvalues.ToString();
txtOutput.Text += arrayvalues + "\t";
arraypos++;
positionvalue++;
}
mergeSort(stringsArray, 0, stringsArray.Length - 1);
txtOutput.Text += "\r\nSorted array: \r\n";
foreach (string i in stringsArray)
{
txtOutput.Text += i + "\t";
}
}
I think the main problem you are facing while using your sort for string is the below line
if (sortArray[lower] <= sortArray[middle])
Because you cannot use <= on two strings. Rather, what you can do is, you can use the string.CompareTo() method. See the MSDN doc on IComparable for string.
Since you can use that in your code, you can change your code to be like
while ((lower <= lowEnd) && (middle <= upper)) //notice the CompareTo
{
if (sortArray[lower].CompareTo(sortArray[middle]) < 1) //<= here
{
temp[low] = sortArray[lower];
low++;
lower++;
}
else
{
temp[low] = sortArray[middle];
low++;
middle++;
}
}
You might need to adjust your last loop and few other minor stuffs.
for (int i = 0; i < n; i++)
{
sortArray[upper] = temp[upper]; //sortArray is string[]
upper--;
}
I want to enter 10 numbers, and then show them in 1 line like this:
1,4,5,2,456,23,... and so on..
and it keeps writing them as I am entering them, and in the end when it's supposed to show all numbers in 1 line it shows only the last one.
I know it's possible with random numbers but when I enter them on my own I don't know how not to show them at all or keep them in 1 line and if it is even possible?
int a;
int x;
Console.WriteLine("a:");
a = int.Parse(Console.ReadLine());
x = 10;
for (int i = 0; i < x; i++)
{
a = int.Parse(Console.ReadLine());
}
Console.ReadKey();
you can use
Console.ReadKey(true)
it reads a key from console and does not show it.
you can use this to read word from console without showing it
public static string ReadHiddenFromConsole()
{
var word = new StringBuilder();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (word.Length > 0)
{
word.Remove(word.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
word.Append(i.KeyChar);
Console.Write("*");
}
}
return word.ToString();
}
You can use this code:
static void Main(string[] args)
{
int length = 10;
int[] myNumbers = new int[length];
for (int i = 0; i < length; i++)
{
Console.Write("Enter number:" );
myNumbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("Your numbers: {0}", string.Join(",", myNumbers));
}
i dont know how to write them at the end all in 1 line?
Well you need to save them as they are entered:
int num;
var nums = new List<int>();
while (nums.Count < 10)
{
Console.Write("Enter: ");
if (int.TryParse(Console.ReadLine(), out num))
{
nums.Add(num);
Console.Clear();
}
}
Console.WriteLine(string.Join(", ", nums));