I have a program that has two text boxes for input. They are variableOne and VariableTwo. I can't figure out the expression that i need to put in the for loop to show these numbers and the numbers in between them. For example if i put a 1 and 11 i need 2-10 in between those. This is what i have so far.. I know i don't have the else expressions yet either.
namespace loops
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void whileButton_Click(object sender, EventArgs e)
{
double variableOne = 0;
double variableTwo = 0;
int i = 0;
if (double.TryParse(variableOneText.Text, out variableOne))
{
if(double.TryParse(variableTwoText.Text, out variableTwo))
{
while(i<= (variableOne) && (variableTwo))
{
i++;
}
outputLabel.Text = i.ToString();
}
}
}
}
}
It's still not clear what you want to achieve.
I make a guess here:
INPUT: two rational numbers.
OUTPUT: all natural numbers in between.
e.g. IN 8.1, 14.9 -> OUT 9, 10, 11, 12, 13
here's the code
StringBuilder output = new StringBuilder();
double variableOne = 8.1;
double variableTwo = 14.9;
double start = 0;
double end = 0;
bool isShowingInitialVariable = true;
//if (double.TryParse(variableOneText.Text, out variableOne))
//{
// if (double.TryParse(variableTwoText.Text, out variableTwo))
// {
//take allways the smaller number to start and the greater for end
start = Math.Min(variableOne, variableTwo);
end = Math.Max(variableOne, variableTwo);
//build your output
output.AppendLine(string.Format("first variable {0}, second variable {1}", variableOne, variableTwo));
output.AppendLine(string.Format("min", start));
output.AppendLine(string.Format("max", end));
output.AppendLine(string.Format("difference {0}", end - start));
//all the natural numbers in between.
for (int i = (int)Math.Ceiling(start); i < Math.Floor(end); i++)
{
output.AppendLine(i.ToString());
}
Console.WriteLine(output.ToString());
// outputLabel.Text = output.ToString();
// }
//}
Related
I have homework. I have to make a program which can input the length of an array with the value in it. After I click the "process" button, the program will make an output of index and value with the result sum and average from the array.
I'm stuck and couldn't print the index and the value to the multiple textbox below process button.
I'm expecting the output will look like this:
Here's the code which I'd been successful write so far:
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i];
}
boxSum.Text = Convert.ToString(sum);
}
}
}
Please, help me.
Here is the code for you (boxAvg is for average)
namespace ArrayProcess
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void process_Click(object sender, EventArgs e)
{
int sum = 0;
string ind = "index";
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i=1; i <= count; i++)
{
varray[i-1] = Convert.ToInt32(Interaction.InputBox(message="enter the value of array number "+i));
sum += varray[i-1];
}
//Refer your list box here to add newly added values to the list
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum / count); //calculate the average
}
}
}
Given that the array already has data :
private void Display()
{
var columnHeader1 = "Index Value\n";
multilineTextBox1.Text =
columnHeader1 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5}"));
boxSum.Text = vArray.Sum();
boxAvg.Text = vArray.Average();
var columnHeader2 = "Index Value Histogram\n";
multilineTextBox2.Text =
columnHeader2 +
string.Join("\n", vArray.Select((x,i)=> $"{i+1,5} {x,5} {new String('*', x)}"));
}
String.Join(separator, string[]), To join each row with a Carriage return/Line feed.
.Select((x,i)=> (...), To get each elment of the array an its index.
$"", For the easy string interpolation
{i+1,5}, To display the index i padded on 5 char.
new String('*', x)}, To create a string of N time the same char.
Console demo
I have 2 arrays one of the types of numbers that will be used and the 2nd array is how many times that number can be used. I have a letter that determines what kind of method will be used I need to figure out how many times I can use a certain number from an array to determine a letter+number The ‘number’ is what I have to make with all the available numbers I can use. If the number cannot be made I would like to just say number cant be made or anything but allow the program to move on.
Here is what I have
int[] picksToUse = { 100, 50, 20, 10, 5, 1 };
int[] timesToUse = { 10, 10, 10, 10, 10, 10 };
string choice = Console.ReadLine();
string input = "";
if(choice.Length > 2)
{
input = choice.Substring(choice.IndexOf("$") + 1);
}
if(...){
}
else if (choice.Equals("D"))
{
int amt = Convert.ToInt32(input);
// code here to determine if number can be made with above choices
Dispense(amt, timesToUse);
}
Assuming picksToUse and timesToUse are exactly the same as you declared them, here's a way to know if you have enough of everything in stock to "pay up". It's a boolean function, which uses recursion. You would call it with the amount needed as parameter, and it would tell you right there if you have enough of everything.
Private Function HasCashInStock(amount As Integer, Optional index As Integer = 0) As Boolean
Dim billsNeeded As Integer = amount \ picksToUse(index)
If billsNeeded > timesToUse(index) Then
Return False
End If
amount -= picksToUse(index) * billsNeeded
If amount = 0 Then
Return True
End If
Return HasCashInStock(amount, index + 1)
End Function
The \ is an integer division operator (in VB.NET, at least - I'm shamelessly letting you translate this code). If you're not familiar with the integer division operator, well, when you use it with integer it gets rid of the floating numbers.
3 / 2 is not valid on integers, because it would yield 1.5.
3 \ 2 is valid on integers, and will yield 1.
That's all there is to it, really. Oh yeah, and recursion. I like recursion, but others will tell you to avoid it as much as you can. What can I say, I think that a nice recursive function has elegance.
You can also totally copy this function another time, modify it and use it to subtracts from your timesToUse() array once you know for sure that there's enough of everything to pay up.
If HasCashInStock(HereIsTheAmountAsInteger) Then
GivesTheMoney(HereIsTheAmountAsInteger)
End If
Having two functions is not the leanest code but it would be more readable. Have fun!
This is what I used to finish my project.
public static bool Validate(int amount, int[] total, int[] needed)
{
int[] billCount = total;
int[] cash = { 100, 50, 20, 10, 5, 1 };
int total = amount;
bool isValid = true;
for (int i = 0; i < total.Length; i++)
{
if(total >= cash[i])
{
billCount[i] = billCount[i] - needed[i];
}
if(billCount[i] < 0)
{
isValid = false;
break;
}
}
return isValid;
}
I got some working code. I did it with a class. I remember when I couldn't see what good classes were. Now I can't brush my teeth without a class. :-)
I force myself to do these problems to gain a little experience in C#. Now I have 3 things I like about C#.
class ATM
{
public int Denomination { get; set; }
public int Inventory { get; set; }
public ATM(int denom, int inven)
{
Denomination = denom;
Inventory = inven;
}
}
List<int> Bills = new List<int>();
List<ATM> ATMs = new List<ATM>();
private void OP2()
{
int[] picksToUse = { 100, 50, 20, 10, 5, 1 };
foreach (int d in picksToUse )
{
ATM atm = new ATM(d, 10);
ATMs.Add(atm);
}
//string sAmtRequested = Console.ReadLine();
string sAmtRequested = textBox1.Text;
if (int.TryParse(sAmtRequested, out int AmtRequested))
{
int RunningBalance = AmtRequested;
do
{
ATM BillReturn = GetBill(RunningBalance);
if (BillReturn is null)
{
MessageBox.Show("Cannot complete transaction");
return;
}
RunningBalance -= BillReturn.Denomination;
} while (RunningBalance > 0);
}
else
{
MessageBox.Show("Non-numeric request.");
return;
}
foreach (int bill in Bills)
Debug.Print(bill.ToString());
Debug.Print("Remaining Inventory");
foreach (ATM atm in ATMs)
Debug.Print($"For Denomination {atm.Denomination} there are {atm.Inventory} bills remaining");
}
private ATM GetBill(int RequestBalance)
{
var FilteredATMs = from atm in ATMs
where atm.Inventory > 0
orderby atm.Denomination descending
select atm;
foreach (ATM bill in FilteredATMs)
{
if (RequestBalance >= bill.Denomination )
{
bill.Inventory -= 1;
Bills.Add(bill.Denomination);
return bill;
}
}
return null;
}
Here's my code:
StreamReader reader = new StreamReader("war.txt");
string input = null;
while ((input = reader.ReadLine()) != null)
{
Console.WriteLine(input);
}
reader.Close();
The program above reads and prints out from the file “war.txt” line-by-line. I need to re-write the program so that it prints out in reverse order, i.e., last line first and first line last. For example, if “war.txt” contains the following:
Hello.
How are you?
Thank you.
Goodbye.
The program should prints out:
Goodbye.
Thank you.
How are you?
Hello.
I am very new in C# please help! Thanks!
To do that, you are going to have to buffer the data anyway (unless you do some tricky work with the FileStream API to read the file backwards). How about just:
var lines = File.ReadAllLines("war.txt");
for(int i = lines.Length - 1; i >= 0; i--)
Console.WriteLine(lines[i]);
which just loads the file (in lines) into an array, and then prints the array starting from the end.
A LINQ version of that would be:
foreach(var line in File.ReadLines("war.txt").Reverse())
Console.WriteLine(line);
but frankly the array version is more efficient.
You can do it using recursion with something like this:
void printReverse(int n)
{
String line = reader.readLine();
if (n > 0)
printReverse(n-1);
System.out.println(line);
}
Have a look at adding the lines to a List, then using Reverse on the list and then maybe the ForEach to output the items.
Another option: store each line into a Stack as you read them. After reading the file, pop the stack to print the lines in reverse order.
with the enumerable extension functions, this can be done shorter:
foreach(var l in File.ReadAllLines("war.txt").Reverse())
Console.WriteLine(l);
try
File.ReadAllLines(myFile)
.Reverse();
full code
var list = File.ReadAllLines(filepath).Reverse().ToList();
foreach (var l in list)
Console.WriteLine(l);
Implementation detail
Enumerable.Reverse Method - Inverts the order of the elements in a sequence
File.ReadAllLines Method (String) - Opens a text file, reads all lines of the file, and then closes the file.
here is a example mate, remember to add "using System.IO"
try
{
const int Size = 7;
decimal[] numbers = new decimal[Size];
decimal total = 0m;
int index = 0;
StreamReader inputfile;
inputfile = File.OpenText("Sales.txt");
while (index < numbers.Length && !inputfile.EndOfStream)
{
numbers[index] = decimal.Parse(inputfile.ReadLine());
index++;
}
inputfile.Close();
foreach (decimal Sales in numbers)
{
outputlistBox1.Items.Add(Sales);
total = total + Sales;
}
textBox1.Text = total.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is another example from a textbook i bought few years ago, this has highest/lowest/average scores..(remember to use 'using System IO;)
private double Average(int[] iArray)
{
int total = 0;
double Average;
for (int index = 0; index < iArray.Length;
index++)
{
total += iArray[index];
}
Average = (double) total / iArray.Length;
return Average;
}
private int Highest(int[] iArray)
{
int highest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] > highest)
{
highest = iArray[index];
}
}
return highest;
}
private int Lowest(int[] iArray)
{
int lowest = iArray[0];
for (int index = 1; index < iArray.Length; index++)
{
if (iArray[index] < lowest)
{
lowest = iArray[index];
}
}
return lowest;
}
private void button1_Click(object sender, System.EventArgs e)
{
try
{
const int SIZE = 5;
int[] Scores = new int [SIZE];
int index = 0;
int highestScore;
int lowestScore;
double averageScore;
StreamReader inputFile;
inputFile = File.OpenText("C:\\Users\\Asus\\Desktop\\TestScores.txt");
while (!inputFile.EndOfStream && index < Scores.Length)
{
Scores[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in Scores)
{
listBox1.Items.Add(value);
}
highestScore = Highest(Scores);
lowestScore = Lowest(Scores);
averageScore = Average(Scores);
textBox1.Text = highestScore.ToString();
textBox2.Text = lowestScore.ToString();
textBox3.Text = averageScore.ToString("n1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}
I am trying to create a word search game. the problem is I am unable to insert words into a TableLayoutPanel. When I wrote this, I got a compile error that says "no overload for method 'placewords' takes '5' arguments.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
for (int a = 0; a < tableLayoutPanel1.ColumnCount; a++)
{
for (int b = 0; b < tableLayoutPanel1.RowCount; b++)
{
Label nl = new Label();
int x = r.Next(65, 90);
char c = (char)x;
nl.Text = c.ToString();
tableLayoutPanel1.Controls.Add(nl, a, b);
}
}
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void PlaceWords()
{
string[] words = { "byte", "char" };
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;// continue trying to place the word in // the matrix until it fits
while (placed == false)// generate a new random row and column
{
int nRow = rn.Next(30);// generate a new random x & y direction vector
int nCol = rn.Next(30);// x direction: -1, 0, or 1
int nDirX = 0; // y direction -1, 0, or 1
int nDirY = 0; // (although direction can never be 0, 0, this is null)
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed =PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY);
}
}
}
Your PlaceWords method doesn't accept that many parameters, in fact, it accepts no parameters.
Further more, the way it looks, your PlaceWords is a recursive function that won't exit, leading to a stack overflow.
To fix this, you need to create a second PlaceWords function that accepts all 5 parameters, and does whatever PlaceWords does, and returns a boolean.
It looks like your nested for loops in Form1_Load should be placing random characters into tableLayoutPanel1. You then need to call PlaceWords() which will determine the location and direction to place each word in the words list. Near the end of PlaceWords you are calling PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY) which is supposed to actually put the word into tableLayoutPanel1. This second PlaceWords with 5 parameters should have a different name (I suggest PlaceString); it should not be trying to call the same Placewords method that it is in.
You need to then write the method PlaceString that will look like:
public bool PlaceString(string s, int nRow, int nCol, int nDirX, int nDirY)
{
/* whatever code you need to put the string into tableLayoutPanel1 */
}