I have 3 methods to 1. Take in strings as an array [zipCodes], 2. Output a menu for the user and 3. display the string array back to the user. The first 2 options are working and after testing I can say that the array is working and taking in strings, however I am having bother displaying them back to the user.
I have used this method with ints, it makes me think that the [i] is only for 1 character, an explanation would be greatly appreciated.
// Here is the code so far
static void Main(string[] args)
{
string[] zipCodes = new string[10];
string zCounter;
for (int i = 0; i < zipCodes.Length; i++)
{
Console.WriteLine("Please enter 10 destinations:");
zCounter = Convert.ToString(Console.ReadLine());
zCounter = zipCodes[i];
}
int sentinalNo;
Console.Clear();
Console.WriteLine("Please enter from the following options: ");
Console.WriteLine("1. Display order zipcodes.");
Console.WriteLine("2. Search zipcode.");
Console.WriteLine("3. Exit.");
sentinalNo = Convert.ToInt32(Console.ReadLine());
while (sentinalNo != 3)
{
switch (sentinalNo)
{
case 1:
DisplayZips(zipCodes);
break;
}
}
}
private static void DisplayZips(string[] zipCodes)
{
for (int i = 0; i < zipCodes.Length; i++)
{
// Why doesnt this work?
Console.WriteLine(zipCodes[i]);
}
You should assign input into the array items:
// array of 10 strings each of them is null
string[] zipCodes = new string[10];
...
for (int i = 0; i < zipCodes.Length; i++)
{
Console.WriteLine("Please enter 10 destinations:");
// Convert.ToString is redundant here
zCounter = Convert.ToString(Console.ReadLine());
// swapped: user input is assigned to array items
zipCodes[i] = zCounter;
}
Related
namespace A3PFJBJLP1
{
class Program
{
static void Main(string[] args)
{
// option 1 by parker farewell
Console.WriteLine("~ option 1 ~");
Console.WriteLine("please input a number: ");
for (int StartingNum = Convert.ToInt32(Console.ReadLine()); StartingNum < 20; StartingNum++)
{
Console.WriteLine(StartingNum);
}
Console.ReadLine();
}
}
}
So far this is the code I've tried and I can display the numbers in a list, but only if the number is 20 or less when I need to make a list that displays 20 whole numbers that come after the number inputted by the user
You were close. If you start at a number userInput, you want to display 20 numbers after it you could update the loop as follows.
int userInput = Convert.ToInt32(Console.ReadLine()); // get and store user input
for (int startingNum = userInput; startingNum < userInput + 20; startingNum++)
{
Console.WriteLine(startingNum + 1); // display number after startingNum
}
This question already has answers here:
Check if a value is in an array (C#)
(10 answers)
Closed 4 years ago.
I'm working on a problem and i've tried it every way I can think of with a for loop but i can't figure out how to make it work as I only started on c# and programming as a whole a few weeks ago.
Write an app that inputs five numbers. As each number is read search the array if the number doesn’t exist in the array output the word “new” and insert the number into the array. If the number does exist in the array output “exists”. Once all five numbers have been entered output the content of the array.
This is what I have so far. Thanks for any help
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
array[i] = Convert.ToInt32(Console.ReadLine());
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
First of all try thinking about a solution before you actually start writing some code, couple of hints
You expect some user input, we will use a variable to save the user input
You need to validate that the values does not exist in you array or structure, this can be done using the Contains method.
If it exists we continue to the next user input and print the required message.
If the value does not exists we add the value and print the new message
We will do this until the Count of the structure is equal to 5.
for reference use this While loop, Hashset.Contains and Hashset
try this:
var numbers = new HashSet<int>();
while(numbers.Count < 5)
{
Console.WriteLine("Enter a number:"); //1.
var number = Convert.ToInt32(Console.ReadLine());
if (numbers.Contains(number)) // 2.
{
Console.WriteLine("exists\n"); //3.
continue;
}
Console.WriteLine("new\n"); //4.
numbers.Add(number);
}
foreach (var n in numbers)
{
Console.WriteLine(n);
}
Use .Any() in System.Linq. Also, you don't need to continuously grab user input in your loop:
using System;
using System.Linq;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// Get user input and convert to integer:
int input = Convert.ToInt32(Console.ReadLine());
// Check if given input is already in the array:
if (! array.Any(number => number == input))
{
array[i] = input;
Console.WriteLine("new\n");
}
else
{
Console.WriteLine("exists\n");
}
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
Edit: Another variant if you want the user to fill the array completely:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
// Btw, if this is not an array of nullables,
// we will not be able to insert a zero later, as
// we will treat them as duplicates.
int?[] array = new int?[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
int input = 0;
bool duplicateAttempt = false;
do {
// Get and convert the input.
input = Convert.ToInt32(Console.ReadLine());
// See if this number is already in.
duplicateAttempt = array.Contains(input);
// Report if we attempt to insert a duplicate.
if (duplicateAttempt) Console.WriteLine("exists");
}
while (duplicateAttempt); // Keep asking while we don't get a unique number.
array[i] = input; // Store the number
Console.WriteLine("new");
}
// Print the contents of array separated by ','
Console.WriteLine(string.Join(", ", array));
Console.ReadKey();
}
}
A couple of issues with your code. You should only increment the array index if successful - otherwise the missing values will be zero. It's also a good idea to validate the input in case the user entered an invalid value. You can use linq to check if the value already exists in the array:
Here's an example:
static void Main(string[] args)
{
int[] array = new int[5];
var index = 0;
while (index < array.Length)
{
Console.WriteLine("Enter a number:");
var input = Console.ReadLine();
var value = 0;
if (!int.TryParse(input, out value))
{
Console.WriteLine("Error - value entered was not a number");
}
else
{
var match = array.Where(a => a == value);
if (match.Any())
{
Console.WriteLine("exists\n");
}
else
{
array[index] = value;
Console.WriteLine("new\n");
index++;
}
}
}
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
This appears to be a homework question, so I think it's more helpful to explain what you've done wrong and tell you what you should do...
It won't help you learn to copy and paste other people's answers.
using System;
public class Program
{
// Main method begins execution of C# application
public static void Main(string[] args)
{
int[] array = new int[5];
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine("Enter a number:");
// you are putting the value into your array here. so it will always 'exist' below
array[i] = Convert.ToInt32(Console.ReadLine());
// you need to do this check before you insert the number into the array
// put the ReadLine into a variable, not directly into the array.
// then check if it's in the array already
for (int a = 0; a < 5; a++)
{
if (array[i] != array[a])
{
// here you are trying to read another value from the user.
// Console.ReadLine() will always wait for user input
// use the variable from above. but only after you have looped through all the items.
// and verified that it is not present
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("new\n");
}
}
// this is the third time you have assigned the number to the array
// and the third time you've asked for user input per loop
array[i] = int.Parse(Console.ReadLine());
Console.WriteLine("exists\n");
}
Console.WriteLine(array);
Console.ReadKey();
}
} // end class
To summarize:
you need a for loop that runs 5 times.
The for loop will do the following:
assign the user input to a variable
loop through your array (second loop) and see if it contains this variable
if the number is found, set a boolean to true. (found)
if after the loop is over, found = false, then print false
also add the number to the array (at the index of the outer loop is fine)
I am trying to get input from user 5 times and add those values to marks array;
Then, it will calculate the average and print positive or negative accordingly. However, I can not take input from the user it just prints "Enter 5 elements". After getting input from user how can I add them to marks array? Any tips would be helpful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
double average =0;
int [] marks = new int[] { };
for (int a = 0; a < 5; a++){
Console.WriteLine("Enter 5 elements:");
string line = Console.ReadLine();
Console.WriteLine(line);
}
for (int i = 0; i < marks.Length; i++){
average = marks.Average();
}
if(average>0){
Console.WriteLine("Positive");
}else{
Console.WriteLine("Negative");
}
}
}
I would use a while loop combined with int.TryParse to check if the user input is a number. Also it doesn't make any sense to put average = marks.Average(); inside a for loop, because LINQ Average calculates the average of a collection (in your case the marks array).
static void Main()
{
int[] marks = new int[5];
int a = 0;
Console.WriteLine("Enter 5 elements:");
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out marks[a]))
a++;
else
Console.WriteLine("You didn't enter a number! Please enter again!");
}
double average = marks.Average();
if (average > 0)
Console.WriteLine("Positive");
else
Console.WriteLine("Negative");
}
DEMO HERE
Edited my answer to illustrate solving your problem without a for loop.
class Program
{
const int numberOfMarks = 5;
static void Main()
{
List<int> marks = new List<int>();
Enumerable.Range(1, numberOfMarks)
.ForEach((i) => {
Console.Write($"Enter element {i}:");
marks.Add(int.TryParse(Console.ReadLine(), out var valueRead) ? valueRead : 0);
Console.WriteLine($" {valueRead}");
});
Console.WriteLine(marks.Average() >= 0 ? "Positive" : "Negative");
}
}
This will help you, just copy and paste it.
There are some explanation with comments.
class Program
{
static void Main()
{
const int numberOfMarks = 5;
int[] marks = new int[numberOfMarks];
Console.WriteLine("Enter 5 elements:");
for (int a = 0; a < numberOfMarks; a++)
{
// If entered character not a number, give a chance to try again till number not entered
while(!int.TryParse(Console.ReadLine(), out marks[a]))
{
Console.WriteLine("Entered not a character");
}
Console.WriteLine("You entered : " + marks[a]);
}
// Have to call Average only once.
var avg = marks.Average();
Console.WriteLine(avg > 0 ? "Positive average" : "Negative average");
Console.ReadLine();
}
}
Follow Stackoverflow Answer
since integer array is being used, and as input from the console is a string value, you need to convert it using Parse() Method. For e.g.
string words = "83";
int number = int.Parse(words);
Edit: using string variable in parsing.
I'm a relatively new student to C# programming and I'm having a lot of trouble with 2-D arrays. In this program the user is supposed to input names, verbs, and objects for an insult generator, but the problem is that I have to pointlessly store them all in one 2-D string array and generate the insults in a 1-D string array and I'm just completely lost. Can I store name, verb, and object into a single 2-D string array? Any help would be appreciated.
My issue is with initializing and storing the 2D string array and then converting to the 1D array.
private static void Generate(int insultnum, int sentnum)
{
int Ncounter = 1;
int Vcounter = 1;
int Ocounter = 1;
string[,] name = new string[sentnum,?];
string[,] verb = new string[sentnum,?];
string[,] insult = new string[sentnum,?];
do
{
Console.Write("Please enter name of #{0}: ", Ncounter);
//length and height 2D array for loop text is just a placeholder from an earlier project
for (int i = 0; i < length; i++)
{
for (int j = 0; j < height; j++)
{
name[Ncounter - 1, ??] = Console.ReadLine();
}
}
//
Ncounter++;
} while (Ncounter < sentnum);
do
{
Console.Write("Please enter name of #{0}: ", Vcounter);
verb[Vcounter-1, ?] = Console.ReadLine();
//2D array loop text
Vcounter++;
} while (Vcounter < sentnum);
do
{
Console.Write("Please enter name of #{0}: ", Ocounter);
insult[Ocounter-1, ?] = Console.ReadLine();
//2D array loop text
Ocounter++;
} while (Ocounter < sentnum);
Ncounter = 0;
Vcounter = 0;
Ocounter = 0;
string[] insults = new string[insultnum];
//insults = name[?,?] + " " + verb[?,?] + " " + object[?,?];
}
Example Output:
Enter the number of insults to generate: 3
Enter the number of names, verbs, and objects: 3
Please enter name #1: Bob
Please enter name #2: Rhys
Please enter name #3: Kaa
Please enter verb #1: licks
Please enter verb #2: touches
Please enter verb #3: tastes
Please enter object #1: dirt
Please enter object #2: cars
Please enter object #3: asphalt
Insults have been generated
Kaa licks dirt
Bob tastes asphalt
Bob licks cars
2D array i.e. string[,] is a bit strange collection to store the data, since it requires that
NameCounter == VerbCounter == ObjectCounter
More natural choice is a jagged array string[][] which allows arbitrary NameCounter, VerbCounter, ObjectCounter. And, please, decompose your solution, split it to number of easy to implement and test methods:
// Random generator for insulting
private Random rgen = new Random();
// 1st index - category (name/verb/insult), 2nd index item within category
private static string[,] data;
private static string[] categories = new string[] {
"name", "verb", "insult",
};
// Input single categore, e.g. Names or Verbs
private static void InputCategory(int category) {
for (int i = 0; i < data.GetLength(1); ++i) {
Console.Write($"Please enter {categories[category]} #{i + 1}: ");
data[category, i] = Console.ReadLine();
}
}
// Input all categories
private static void InputData() {
Console.Write($"Enter the number of names, verbs, and objects: ");
// simplest; more accurate implementation uses int.TryParse()
int n = int.Parse(Console.ReadLine());
data = new string[categories.Length, n];
foreach(var int i = 0; i < categories.Length; ++i)
InputCategory();
}
To write an insult generator you should combine random items from each category
private static string[] Insults(int count) {
string[] result = new string[count];
// take count times a item from each category
for (int i = 0; i < count; ++i) {
StringBuilder sb = new StringBuilder
for (int c = 0; c < categories.Length; ++c) {
if (c > 0)
sb.Append(' ');
sb.Append(data[c, rgen.Next(data.GetLength(1))]);
}
result[i] = sb.ToString();
}
return ressult;
}
Having these methods you can put easily
private static void Main() {
int numberOfInsults = ....
InputData();
foreach (var insult in Insults(numberOfInsults))
Console.Write(insult);
...
}
I'm making a program that accepts values into an array, but if you attempt to input the same value twice, it rejects, if the value is unique, go on.
using System;
public class Program
{
public static void Main()
{
char[] charray = new char[7];
Console.WriteLine("Enter 7 unique alphabetic characters: ");
for (int i = 0; i < charray.Length; i++)
{
charray[i] = Convert.ToChar(Console.ReadLine());
for (int j = 0; j < charray.Length; j++)
{
if (charray[i] == charray[j])
{
Console.WriteLine("Please enter a unique alphabetic character.");
}
}
}
Console.WriteLine(charray);
}
}
Can someone tell me what's wrong?
you're comparing every element in your array with what you just assigned to an element in your array, so of course you'll always find a duplicate... with the item you just entered.
What you actually want is:
void Main()
{
char[] charray = new char[7];
Console.WriteLine("Enter 7 unique alphabetic characters: ");
for (int i = 0; i < charray.Length; i++)
{
var x = Convert.ToChar(Console.ReadLine());
if (charray.Contains(x))
{
Console.WriteLine("Please enter a unique alphabetic character.");
i--;
}
else
{
charray[i] = x;
}
}
Console.WriteLine(charray);
}
By the way this approach is quite slow specially if you extend your array, 7 is fine but the level of optimization is very poor, you might want to look at concept of Hash map. And like the others said, since you first insert the input inside your array, the for will always find your input inside and return duplicated, you might want to check the duplication before insertion operation.
I would like to propose the following implementation:
char[] charArray = new char[7];
Console.WriteLine("Enter {0} unique alphabetic characters: ", charArray.Length);
int i = 0;
while (i < charArray.Length)
{
char inputChar = Console.ReadKey().KeyChar;
Console.WriteLine();
if (charArray.Contains(inputChar))
{
Console.WriteLine("Please enter a unique alphabetic character.");
}
else
{
charArray[i] = inputChar;
++i;
}
}
Console.WriteLine(charArray);