converting for loop to foreach - c#

So I have this piece of code that works fine, how ever for my assignment the professor wants the code to work with a foreach statment. The only way I could get it to work was with a for loop. Anyone know how to convert the for loop into a foreach statment?
here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CheckZips.cs
{
class Program
{
static void Main(string[] args)
{
int[] zips = new int[10] { 07950, 07840, 07828, 07836, 07928, 07869, 07849, 07852, 07960, 07876 };
int correctZipCode;
int input;
Console.WriteLine("Enter a zip code.");
input = int.Parse(Console.ReadLine());
correctZipCode = Convert.ToInt32(input);
bool found = false;
for (int i = 0; i < zips.Length; ++i)
{
if(correctZipCode == zips[i])
{
found = true;
break;
}
}
if (found)
{
Console.WriteLine("We deliver to that zip code.");
}
else
{
Console.WriteLine("We do not deliver to that zip code.");
}
}
}
}

A foreach can be implemented like this:
foreach (int zip in zips)
{
if (zip == correctZipCode)
{
found = true;
break;
}
}

Related

When executing second for loop into listbox program populates no data

so the assignment is to read from the student file into an array and read into the answer key array, compare the two and output a grade based on the array comparison.
the issue i'm having is that when i try to load the answer key into it's array it's like its not even getting the data, because all the questions output as wrong.
below is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AshleyBrown_CPT185A01S_Chapter7Lab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//variables
private const int SIZE = 20; //current # of q's on test
private int index = 0, count = 1; //counter variables
private int wrong = 0, right = 0; //grade variables
these are the arrays that are used for the answers:
//arrays
private char[] studentAnswers = new char[SIZE];
private char[] answerKey = new char[SIZE];
private void calculateBtn_Click(object sender, EventArgs e)
{
//prevents any file errors
try
{
ReadStudentFile();
ReadAnswerKey();
CompareAnswers();
}
catch
{
MessageBox.Show("File doesn't exist or has the wrong name.");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
//Clear Form
studentAListBox.Items.Clear();
correctAListBox.Items.Clear();
wrongAListBox.Items.Clear();
incorrectBox.Text = "";
correctBox.Text = "";
percentBox.Text = "";
}
private void exitBtn_Click(object sender, EventArgs e)
{
//close program
Close();
}
method for reading the student file that works:
private void ReadStudentFile()
{
//Stream Reader Setup
StreamReader studentFile;
studentFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Student File.txt");
//Read Student Answers into studentAnswers Array
while (index < studentAnswers.Length && !studentFile.EndOfStream)
{
studentAnswers[index] = char.Parse(studentFile.ReadLine());
index++;
}
//Close Student Answer file
studentFile.Close();
//Display Student Answers
foreach (char answer in studentAnswers)
{
studentAListBox.Items.Add(count + ". " + answer.ToString());
count++;
}
}
method for reading answer key that populates with no data:
private void ReadAnswerKey()
{
//Stream Reader Setup
StreamReader answerFile;
answerFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Answer Key.txt");
//Read Answer Key in answerKey Array
while (index < answerKey.Length && !answerFile.EndOfStream)
{
answerKey[index] = char.Parse(answerFile.ReadLine());
index++;
}
//Close answer key file
answerFile.Close();
//clear count
count = 1;
//display answer key in correct answer list box
foreach (char key in answerKey)
{
correctAListBox.Items.Add(count + ". " + key.ToString());
count++;
}
}
private void CompareAnswers()
{
//reset count
count = 1;
for (index = 0; index < answerKey.Length; index++)
{
//determine if answer is right
if (studentAnswers[index] != answerKey[index])
{
wrongAListBox.Items.Add(count + ". " + answerKey[index]);
wrong++;
count++;
}
}
//fail display
if (wrong > 5)
{
MessageBox.Show("Student has failed");
}
//calculations
double pointPerQ = 5;
double wrongTotal = wrong;
double wrongPointTotal = wrong * pointPerQ;
double grade = 100 - wrongPointTotal;
//output grade information
incorrectBox.Text = wrong.ToString();
correctBox.Text = right.ToString();
percentBox.Text = grade.ToString("p0");
}
}
}
this is the current output from running the program, I did double check the file names and contents as well.
output of current code
One issue that I saw in code is using of index in multiple while loops without previously assigning to 0.
I suggest using of local variables(variable which exists only in the current block of code).
Also in my opinion it will be good to declare and initialize new variable in for-loop like this:
for(int index = 0; index < answerKey.Length; index++)
{
// your code
}
it will be more readable and easier if you want later to separate loops in methods or move in service or helper.

How do I remove the input halt to automate the input?

So basically the program does what it is supposed to do. The two patterns have to be split with an open line. But I did something wrong now the input wont go in smoothly. I have to press enter a couple of times. The Expected input is:
...........*........
....*.....*.........
.........*..*...*...
*..*..*......***....
..*.....*...........
.*..................
.......*.........*.*
....................
.....*............*.
..........
.*.**.*...
*....*.*.*
..........
..*.....*.
and Output should be
...................*
.................**.
..............***...
........******......
......**............
.....*..............
..***...............
....................
**..................
..........
......****
..****....
..........
**........
But mine looks like this
...........*........
....*.....*.........
.........*..*...*...
*..*..*......***....
..*.....*...........
.*..................
.......*.........*.*
....................
.....*............*.
...................*
.................**.
..............***...
........******......
......**............
.....*..............
..***...............
....................
**..................
..........
.*.**.*...
*....*.*.*
..........
..*.....*.
......****
..****....
..........
**........
I have to press enter a couple of times to get this.
My Code looks like this
using System;
using System.Runtime.CompilerServices;
using Microsoft.VisualBasic;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void defragDisk(Queue<string> diskLine) // Method that will move all the Starsto the right
{
int lnLength = 0;
int iIndex = 0;
int iStars = 0;
int iTotalStars = 0;
while (diskLine.Count > 0)
{
var line = diskLine.Dequeue();
lnLength = line.Length;
iIndex = lnLength - 1 - iTotalStars;
iStars = line.Count(x => x == '*');
iTotalStars += iStars;
var rangeFrom = iIndex - iStars + 1;
var availableIndexes = Enumerable.Range(rangeFrom, iStars).ToDictionary(x => x);
for (int i = 0; i < lnLength; i++)
{
if (availableIndexes.ContainsKey(i))
Console.Write("*");
else
Console.Write(".");
}
Console.Write("\n");
}
}
static void populateQueue(Queue<string> diskLine) // I am using a queue as the sizes can vary without indication
{
bool bCompleted = false;
while (!bCompleted)
{
var line = Console.ReadLine();
if (line == "")
{
bCompleted = true;
break;
}
else
{
diskLine.Enqueue(line);
}
}
}
public static void Main()
{
bool bCompleted = false;
Queue<string> diskLine = new Queue<string>();
while (!bCompleted)
{
populateQueue(diskLine);
defragDisk(diskLine);
diskLine.Clear();
if (Console.ReadLine() == "")
{
bCompleted = true;
break;
}
}
}
}

Save and load a game by using StreamWriter and ReadWriter (C#)

I'm creating a small program which can save and load char array values. Then, I got stuck with two problems.
I have no idea how to make the program end after saving the data.
After loading the char array, it looks the game starts where I saved last time. However, when I put "#" on the place where is already marked, it is accepted. (It is supposed to display error message)
This is when I start new game.
It displays error message properly.
Here is class which includes streamWriter and streamReader.
public class History
{
public char QUIT = 'Y';
public char CONTINUE = 'N';
public char inputGameContinue;
public void WriteFile(char []arr)
{
FileStream sb = new FileStream("MyFile.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(sb);
WriteLine("If you want to save the data, enter" + QUIT +"| To continue, enter "+CONTINUE );
inputGameContinue = char.Parse(ReadLine());
if(inputGameContinue=='Y')
{
sw.Write(arr);
WriteLine("The data is saved!");
}
sw.Close();
}
public void ReadFile()
{
string path = "MyFile.txt";
WriteLine("New game? >> 1 | Load saved data? >>2 ");
int command = int.Parse(ReadLine());
if (command == 2)
{
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
WriteLine(sr.ReadLine());
}
}
}
}
}
Class2
using System;
using static System.Console;
using System.IO;
namespace createSample
{
public class writeRead
{
public static void Main(string[] args)
{
InputClass inputClass = new InputClass();
ArrayValue arrayValue = new ArrayValue();
History history = new History();
WriteLine("Welcome to game!");
WriteLine("");
history.ReadFile();
do
{
inputClass.inputNumber();
while (true)
{
if (arrayValue.arr[inputClass.input] == '#')
{
WriteLine("{0} already marked '#'. Try another.", inputClass.input);
inputClass.inputNumber();
}
else
{
arrayValue.arr[inputClass.input] = '#';
arrayValue.printArray();
history.WriteFile(arrayValue.arr);
break;
}
}
}
while (checkWhenFinish(arrayValue)!=1 );
WriteLine("All letters are marked with '#'");
Read();
}
public static int checkWhenFinish(ArrayValue a)
{
if(a.arr[0] != '0' && a.arr[1] != '1' && a.arr[2] != '2' && a.arr[3] != '3' && a.arr[4] != '4')
{
return 1;
}
else
{
return 0;
}
}
}
}
Class3
using System;
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace createSample
{
public class ArrayValue
{
public char []arr = { '0','1', '2', '3', '4' };
public void printArray()
{
WriteLine("{0},{1},{2},{3},{4}", arr[0], arr[1], arr[2], arr[3], arr[4]);
}
}
}
Class 4
using System;
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace createSample
{
public class InputClass
{
public int input;
public void inputNumber()
{
while (true)
{
Write("Enter number ? (0 to 4) >> ");
if (!int.TryParse(ReadLine(), out input))
{
input = -1;
}
if (input == 0|| input == 1 || input == 2 || input == 3 || input == 4 )
{
break;
}
else
{
WriteLine("Error! Try again!");
}
}
}
}
}
The problem is when you call history.ReadFile() it can read the file and display its contents, but it never updates arrayValue.arr so when the check is done later, arrayValue.arr[inputClass.input] is still 2.
You might want to pass in arrayValue by reference to ReadFile() to have it updated:
history.ReadFile(ref arrayValue);
then in History
public void ReadFile(ref ArrayValue arrayValue)
{
...
while (sr.Peek() >= 0)
{
var line = sr.ReadLine();
WriteLine(line);
for (int i = 0; i < arrayValue.arr.Length; i++)
{
arrayValue.arr[i] = line[i];
}
}
...
}

Cannot get int to be displayed in text box for dice roller app

I'm trying to get back into programming and I'm having trouble getting the final int answers into the text boxes at the end. It has been a few years since I've coded, so if I messed up big time, please let me know.
{
int dice_total;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
string Succ;
string Comp;
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
Succ = succ_num.ToString();
Comp = comp_num.ToString();
}```
[your text box name].Text=[some int].ToString();
For example:
label1.Text = product.BuyingPrice.ToString();
I can't seem to get it count up the successes. For those who don't know, WoD has you roll d10s and you are given a difficulty. You have to roll that difficulty number or higher to get successes. If there are more (or equal) 1s than total successes, its a complication. This isn't even including code for when you roll a 10 (which has you roll again while still counting as a success).
Ex. Roll 5d10s with a difficulty of 6
6, 8, 10, 1, 1 = 3 success
Roll again for the 10: 1
Total: 3 successes and a complication
using Accord.Math.Distances;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Roller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int dice_total;
int dice_add;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
public void button1_Click(object sender, EventArgs e)
{
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
for (dice_add = 0; dice_add < dice_total; dice_add++)
{
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
}
Succ.Text = succ_num.ToString();
Comp.Text = comp_num.ToString();
}
}
}

Removing a line from a text file in C#

i am a newbie in C# and i have a simple console application with method validateVoters() which takes a studentID argument, compares it against text file then return appropriate boolean value.
However i want it to delete that specific studentID if it exists then return true, but there is no generic delete from file method so i used a method recommended by a member here:
Giving me an error with the method in double asterics ** :
Error 2
The name 'RemoveUnnecessaryLine' does not exist in the current context c:\Users\Hlogoyatau\Documents\Visual Studio 2010\Projects\Ijoo\Ijoo\Program.cs 28 43 Ijoo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace SRCVotingSystem
{
public class Program
{
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
foreach (string line in ID)
{
//compares it against text file contents
if (cisNo == line)
{
string[] allLines= File.ReadAllLines("votersRoll.txt");
string[] newIDs= **RemoveUnnecessaryLine**(allLines);
File.WriteAllLines("votersRoll.txt", newIDs);
found = true;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
public static void Main()
{
Program vv = new Program();
Console.WriteLine(vv.validateVoter("cis11-005"));
}
}
}
/* sample data in text.tx
ID 1 asdfsdaf
ID 2 asdfdsafasdfsadf
ID 3 lkjasdfjsdf
*/
private static void Main(string[] args)
{
var id = 2;
var lines = File.ReadAllLines("C:\\temp\\text.txt");
var remaining = lines.Where(x => !x.Contains(id.ToString())).ToArray();
File.WriteAllLines("C:\\temp\\out.txt", remaining);
}
Try this:
public bool validateVoter(String cisNo)
{
bool found = false;
try
{
string[] ID = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt");
for (int i = 0; i < ID.Length; i++)
{
string line = ID[i];
//compares it against text file contents
if (cisNo == line)
{
//Shift remaining lines up, overwriting current line
for (int j = i; j < ID.Length - 1; j++)
{
ID[j] = ID[j+1];
}
//Set last line to empty string
ID[ID.Length - 1] = "";
//Write file back to disk
System.IO.File.WriteAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", ID);
found = true;
//Exit loop after something is found
break;
}
}
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
return found;
}
It will read the file, and when a match is found, then it shifts the remaining lines up one line. The last line will be cleared, then the file gets written back to disk. If you do not want to have an empty last line, then you can resize the array (see Array.Resize).
Try using LINQ
public void validateVoter(String cisNo)
{
var newIDs = System.IO.File.ReadAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt").Where(l => l != cisNo);
File.WriteAllLines(#"C:\Users\Hlogoyatau\Pictures\votersRoll.txt", newIDs);
}

Categories

Resources