Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
here is my code with the comments. so im having trouble exiting out of the loop. i know it shoud be if(contd = true) or something then it should exit out, but also if they enter Y to keep going, how do i get back into the loop?
another thing is how to sort this by abc order. and then how do i do the reverse from Z-A. Thanks for your help, clueless beginner here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string lastName;
string [] lastName = new string[]; //array list of last names
int index;
string contd;
for (index=0;index++)
{
Console.Write("Enter a last name: ");
lastName[index] = Convert.ToString(Console.ReadLine());
Console.Write("Keep going? (Y/N): ");
//prompts user to keep inputting or exit out
contd = Convert.ToString(Console.ReadLine());
if (contd = "n"(Console.ReadLine());
{
//exit out of last name input
}
else contd = "y"(Console.ReadLine());
{
//go back into last name input
}
}
Console.WriteLine((index+1) + " last names entered");
//shows how many last names were entered
Console.WriteLine(); //spacing
//display last names
Console.WriteLine("Names in Acsending Order"); Console.WriteLine();
for(index=0; index++)
//shows the last names in order from A-Z (acsending)
{
Console.WriteLine(lastName[index]);
}
Console.WriteLine();
Console.WriteLine("Names in Descending Order"); Console.WriteLine();
for(index=0; index--)
//shows back last names in reverse order Z-A (descending)
{
Console.WriteLine(lastName[index]); Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use a do while loop:
string d = string.Empty;
do
{
Console.WriteLine("What's your answer?");
d = Console.ReadLine();
}
while (d != "Y");
as for sorting you can use Array.Sort
Array.Sort(array);
You were doing assignments instead of comparisons, and you also ended your if statement lines with a semicolon. The assignment just sets contd to n instead of checking if that is its current value and the semicolon at the end would be overlooking the following braces completely like the following..
if(contd == "n")
;
Which is valid code (not sure why you'd want to do this though). Below is what you seem to be looking for but I still think your for loops are a bit strange
contd = Console.ReadLine(); // Already a string..
if (contd == "n")
{
//exit out of last name input
break;
}
else
{
//go back into last name input
}
To sort these names alphabetically you would be best to look into sorting algorithms such as bubble sort. You could always use linq but I'd imagine this is outside of your classes scope
lastName = lastName.OrderBy(x => x).ToArray();
lastName = lastName.OrderByDescending(x => x).ToArray();
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this is my program I hope you understand what I am trying to do.
if (primeNum = int)
{
Console.WriteLine(" the number entered is not prime ");
}
If you want to know if it's a whole number, then round it and compare the numbers. If the number is a whole number, it will not change when it's rounded...so if the rounded version of the number is equal to the number itself, then it's a whole number. If they're different, then it's not a whole number:
double i = 1.2;
if (Math.Round(i, 0, MidpointRounding.AwayFromZero) == i) {
//whole number
} else {
//not a whole number
}
private static bool IsWhole(double number)
{
return (number % 1 == 0);
}
If Program.isWhole(5.67) returns true call System.Environment.Exit(0) to close application.
Try this program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace primeCsharp
{
class Program
{
static void Main(string[] args)
{
int n = 0; // Number to be test for prime-ness
int i = 2; // Loop counter
bool is_prime = true; // Boolean flag...
// Assume true for now
Console.WriteLine("Enter a number and press ENTER: ");
n = Console.Read();
// Test for a prime number by checking for divisiblity
// by all whole numbers from 2 to sqrt(n).
while (i <= Math.Sqrt(n))
{
if (n % i == 0)
{ // If i divides n,
is_prime = false; // n ix not prime
break; // BREAK OUT OF THE LOOP NOW!
}
++i;
}
// Print results
if (is_prime)
{
Console.WriteLine("Number is prime.\n");
}
else
{
Console.WriteLine("Number is not prime.\n");
}
}
}
}
See this:
How can I get the data type of a variable in C#?
and try:
if(primeNum.GetType() == typeof(int))
You can check whether the number is equal to the value of its conversion to int, like this:
if (primeNum == (int)primeNum)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am writing a program that finds the number of 1's in an array.. but the "scanning" inside the "for" loop takes place only once.
for (i = 0; i < 11; i++ )
{
k = Convert.ToInt32(Console.Read());
if (k==1)
{
ans++;
}
// Console.WriteLine("i == {0}", i);
}
Is this normal in C# or am I doing something wrong? I tried to search for this problem but cannot find any answers!
Do
Console.ReadLine()
instead of
Console.Read()
When you reach the first Console.Read() the inputstream is saved but only the first character is returned by the Read method. Subsequent calls to the Read method retrieve your input one character at a time from the inputstream.
Ex:
First iteration:
k = Console.Read(); //you input "abc1", k = a
Second iteration:
k = Console.Read(); // k = b
and so on.
When the last character in the inputstream is returned, the next call to Console.Read() will display the console again so you can input a new string and hit Enter.
Console.Read() docu
There's no array in your code, actually. Personally I'd rewrite this to:
string input = Console.ReadLine();
for (i = 0; i < input.Length; i++ )
{
int k = Convert.ToInt32(input.Substring(i, 1));
if (k==1)
{
ans++;
}
}
Which lets the user enter a string first and then does all the parsing. Of course, the user may enter more or less than exactly 11 characters in this code, so if you really need 11 numbers, I'd add extra messages and checks.
Also this code (as your original code) fail miserably if the user enters something non-numeric, so exception handling would be on the task list as well.
Try to use this code, I think it will answer your problem
string[] sample = { "1", "1", "3" };
var a = (from w in sample
where w == "1"
select w).ToList();
Console.Write(a.Count);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Facing this problem all the time but couldn't really figure out how to overcome with it;
It is related with the user entry - in case the user enters something wrong I want the program to continue or reask the question;
an example ;
I want the user to enter the age
when the user enters the age correctly I want the program to continue (but in below code it asks 5 times
if the user enters a wrong entry (i.e string) I want the program to reask to enter the age
Vm appreciate to hearing your kind assitance
for (int i = 0; i < 5; i++)
{
int _Age;
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if (!AgeCheck)
{
Console.WriteLine("Please enter your age : ");
}
else
{
i--;
continue;
}
}
int age = 0;
while (true)
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
if (int.TryParse(entry, out age)) break;
}
The idea is simply to run an "infinite" loop until a valid age is entered, at which point we break out of the loop.
Instead of the infinite loops:
int age = 0;
do
{
Console.WriteLine("Please enter your age:");
string entry = Console.ReadLine();
} while (!int.TryParse(entry, out age));
Nothing wrong with the infinite loop inherently. I just think it's cleaner without.
infinite loop, just issue a "break;" and it will drop out....
int _Age;
while( true )
{
Console.Write ("Please enter your age :")
string AgeEntry = Console.ReadLine();
bool AgeCheck = Int32.TryParse(AgeEntry, out _Age);
if ( AgeCheck == true ) { break; }
}
Answer to your question about the question being asked 5 times. You have a for loop that will spin through the code 5 times regardless of the answer the user gives.
for (int i = 0; i < 5; i++)
{ your code is here }
In the code below, after the do loop, you'll have the input from the console in the answer variable and the parsed int in the age variable. You can create a new console app in VS and paste this into Program.cs and run it to test.
using System;
namespace console {
internal class Program {
private static void Main( string[] args ) {
int age;
string answer;
do {
Console.Clear();
Console.Write( "Please enter your age: " );
answer = Console.ReadLine();
} while ( !int.TryParse( answer, out age ) );
Console.WriteLine( string.Empty );
Console.WriteLine( "Thanks, let's continue..." );
Console.Read();
}
}
}
I am new to programming and I have a project in my Algorithm class. What we have to do is decide on a problem and solve it. We haven't learnt much more than string, char and WriteLine. We did add a couple of things as you will see soon!
I decided that what I want to solve this: The user inserts a word, no matter how long and the program will automatically make the first letter a capital letter. So far this is what I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
start:
Console.WriteLine("Please enter a word below:");
Console.WriteLine("");
string str = Console.ReadLine();
char char1;
if (str[0] >= 97)
{
char1 = (char)(str[0] - 32);
}
else
{
char1 = (char)(str[0] + 32);
}
char char2 = (char)(str[1]);
char char3 = (char)(str[2]);
char char4 = (char)(str[3]);
char char5 = (char)(str[4]);
Console.WriteLine("");
Console.Write(char1);
Console.Write(char2);
Console.Write(char3);
Console.Write(char4);
Console.WriteLine(char5);
goto start;
}
}
}
The problem with that code is that any word with less than 5 letters will make the program crash. Anything with more than 5 letters will just be cut at the fifth letter... I was told that using arrays should solve this problem. Seeing as I am a total newbie at this, I would need this to be broken down and be as simply told as possible!
Any help getting this to work would be very appreciated.
Thanks :)
Console.WriteLine("Enter a word:");
string str = Console.ReadLine();
Console.WriteLine(str[0].ToString().ToUpper() + str.Substring(1));
This will work.
Or... if you need to go through the entire string and find the first actual alphabetical character, you can do the following:
Console.WriteLine("Please enter a word:");
string s = Console.ReadLine();
bool found = false;
char[] chars = new char[s.Length];
for (int i = 0; i < s.Length; i++)
{
if (Char.IsLetter(s[i]) && !found)
{
chars[i] = s[i].ToString().ToUpper()[0];
found = true;
}
else
{
chars[i] = s[i];
}
}
s = new String(chars);
Console.WriteLine(s);
Use a for loop like this after writing char1 to the Console:
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)// Start at 1 to skip char1
{
Console.Write(str[i]);
}
}
There are some methods you can call on string that will be helpful:
Substring
ToUpper
In fact, you don't need to worry about characters; this problem can be solved using only strings.
Also take care to check that your code handles the case where the string is empty (using an if statement), which will happen if the user just presses Enter without typing anything.
You're taking an algorithms class and they make you choose a problem to solve? Sounds dangerous for someone learning.
Console.WriteLine("Please enter a word below:");
Console.WriteLine("");
string inputString = Console.ReadLine(); // try to use meaningful variable names
// shorthand for the if ... else block:
// type variableName = (true/false condition) ? "is true" : "is false";
char firstChar = inputString[0] >= 97 ? (char)(inputString[0] - 32) : (char)(inputString[0] + 32);
Console.WriteLine("");
Console.Write(firstChar);
for (int i = 1; i < inputString.Length; i++) // skip firstChar
{
Console.Write(inputString[i]);
}
As others have mentioned, you need to use a loop for this if you want anything resembling a general solution.
Also, you'll want to avoid using goto statements. There are many reasons, one being that they (in my opinion) make code difficult to read and maintain.
Additionally, if your code had worked as written, it would never end. Your program, as written would execute, then begin again, never stopping. If you want this sort of behavior, then you should wrap your code in an infinite loop which exits upon some condition. This might look something like:
bool keepRunning = true;
while(keepRunning){
//code here
Console.Write("go again? (y/n) ");
keepRunning = (string)(Console.ReadLine()).equals("y") ? false : true;
}
On that last statement, I forget if you need to cast the output of ReadLine to a string before calling the .equals method... I don't have my IDE up. i think you get the idea.
edit: I saw another response that was just posed about using the .ToUpper method. I thought of this but assumed maybe you needed to use the char type.
So I'm having a couple of troubles with my code. For starters, I have this problem which is outputting all of the arrays. Mind you I have only been coding for 12 days and my teacher has somewhat skipped over the very basics in C# coding due to my college's outlook on learning. AND I just learned that it doesn't order them alphabetically.....
static int inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
pl[i] = Console.ReadLine();
}
while (pl[i++].CompareTo("Q") != 0);
//if they write Q for the player it will quit
return i - 1;
}
static void Main(string[] args)
{
String[] players = new String[100];
Array.Sort(players);
// Sort array.
//defines players in this new instance
var count = inputPartInformation(players);
//for the portion of the code that handles the input
//calculates the average score
Console.WriteLine("List of People in Order: {0}, {1}, {2}, {3}, {4}, {5}, {6},", players);
Console.ReadLine();
}
}
}
You are sorting before the names are populated; that does nothing.
You are printing a single item using a fixed multi-item list of parameter references {0}, {1},{2} and so on; it is not going to work, and even if it did it would limit your output to the first seven items
You do not know how many items to sort. Change void inputPartInformation(string[] pl) to return count (which is i-1), and use Array.Sort(players, 0, count);
The simplest way to convert multiple strings into a single string is by using string.Join:
Console.WriteLine("List of People in Order: {0}", string.Join(", ", players.Take(count)));
First, "Q" is being added to the input list because you don't test for "Q" until after the input has been accepted and inserted into your array. One way of reworking this would be to hold the input name into a temporary variable, test that for "Q", and add it to your array only if it is something else. Within your loop, modify your input/test to something like:
bool enteringNames=true;
do{
String nextName = Console.ReadLine();
if (nextName.CompareTo("Q")==0)
{
enteringNames=false;
}
else
{
p[i]=nextName;
}
i++;
}
while(enteringNames);
This is just one way of getting the job done. Keep in mind that a fixed 100-entry array isn't the most robust way of doing this...never know how many names might be going in!
Now, the last WriteLine is a bit odd, but I think you can figure that part out on your own - its pretty straightforward to either iterate through the array, or just join all the strings together :)
Second, your sort isn't working because you call Array.Sort(players) before you call inputPartInformation(players) to actually load the data - so you're sorting without any data!. Move the Array.Sort call after the call to inputPartInformation.
Hope this helps!
Try this, it will work, but first try to study about the APIs
static int inputPartInformation(string[] pl)
{
int i = 0;
String temp;
while (true)
{
Console.Write("Enter a Name: ");
temp=Console.ReadLine();
if (temp=="Q")
break;
else pl[i++] = temp;
}
return i;
}
static void Main(string[] args)
{
String[] players = new String[100];
int size=inputPartInformation(players);
for (int i = 0; i <= size; i++)
Console.WriteLine(players[i]);
}
}
Q is appearing in your outcome because you are assigning it to your array.
Rewrite you function to check the value before you assign it, for example
static void inputPartInformation(string[] pl)
{
int i = 0;
do
{
Console.Write("Enter a Name: ");
//for the player
newStrInput = Console.ReadLine();
if (newStrInput == "Q")
break;//if they write Q for the player it will quit
pl[i]=newStrInput;
i++;
}
while (i>-1);//infinite loop
}