C#. Console.ReadLine() for two different obejcts [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm learning C# and very new to this topic. Currently, I'm working on a small console app (just doing tasks to strengthen my knowledge) Battleship game. I want to assign two names: Player 1 and Player 2.
Question is: Can I use one reader instead of two, to assign different names? I tried to use one reader, but it assigned one name to both players.
Here is my code:
public void StartGame(Game game)
{
if (game.GameStage == GameStage.Start)
{
Console.WriteLine("Welcome to Battleship 2020.");
Console.WriteLine("Player 1 enter your name:");
var reader1 = Console.ReadLine();
Player player1 = new Player();
player1.Name = reader1;
Console.WriteLine($"Welcome {player1.Name}");
Console.WriteLine("Player 2 enter your name:");
Player player2 = new Player();
var reader2 = Console.ReadLine();
player2.Name = reader2;
Console.WriteLine($"Welcome {player2.Name}");
}
}

Console.ReadLine() does not return any "reader". It just returns String object which contains text grabbed from console input.
The line in method name means it will read everything available on the input until it will encounter line break.
If there is no line break, it will wait forever until user will press "enter" key.
If there are many text lines in the bufffer, you need to call ReadLine() many times.
You can assign player name diretly using:
player1.Name = Console.ReadLine();

If you want to get both player names in one read, (you may first prompt the user) and tell them to enter players name comma or space separated and then after reading the player names separate them yourself
var reader = Console.ReadLine();
var playerNames = reader.Split(' '); // payerNames[0], playerNames[1] contains player names
If you mean just to reuse the reader variable. you can use it any times you want but the first time you need to declare it.
var reader = Console.ReadLine();
...
reader = Console.ReadLine();
...
reader = Console.ReadLine();
You may put this in a loop like:
for(int i = 0; i < 2; i++)
{
var reader = Console.ReadLine();
...
}
if you want to make sure that no empty value is entered, you may use do...while and loop till a valid value is set. (retry on empty or invalid values):
for(int i = 0; i < 2; i++)
{
do
{
player[i] = Console.ReadLine();
} while(player[i].Trim() != "");
}

Related

How do I exit a for loop with a key press? [duplicate]

This question already has an answer here:
exit with escape key in for loop
(1 answer)
Closed 5 years ago.
For my ASSIGNMENT, I am running this loop to gather id #'s and names in a 2d array.
But I would like to be able to break out of the loop if the user doesn't want to sit and enter 30 sets of numbers and names. Because... why would they?!
string[,] studentNames = new string[30,30];
// Accepting value from user
for (i = 0; i < 30; i++)
{
Console.Write("\nEnter id #, Student Name :\t");
//Storing value in an array
studentNames[i, 0] = (Console.ReadLine());
}
I've tried adding:
do
{
//the stuff
} while(Console.ReadKey().Key != ConsoleKey.Escape);
But that doesn't work.
You can use something like this:
readLine = (Console.ReadLine());
if(readLine == "exit") break;
studentNames[i, 0] = readLine;
That will exit if user input the word exit. Depending on the language, the comparation readLine == "exit" may have to be replaced by some string comparing funcition.
I hope it helps.

Application Not Working Correctly C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My code isn't storing a response as user input. It jumps to the else statement every time I get here. Then it throws the sum as 50? When I store input like Value of first number = 2 and value of second = 3.
I'm doing a class at home and I have been working for a few hours trying to figure out why my code doesn't work right.
C#, below:
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
bool stopOrContinueAdding = true;
do
{
string inputMoreNumbers = Console.ReadLine();
switch (inputMoreNumbers.ToLower())
{
case "a":
inputMoreNumbers = "a";
stopOrContinueAdding = false;
break;
case "b":
inputMoreNumbers = "b";
stopOrContinueAdding = true;
break;
default:
stopOrContinueAdding = false;
break;
}
if (stopOrContinueAdding == false)
{
int sum = aNum.Sum();
Console.WriteLine("Here is the sum of your numbers: " + sum );
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Redirecting to main menu...");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
isInputValid = false;
}
else
{
Console.Clear();
Console.Write("Value of next number: ");
number++;
aNum[number - 1] = Convert.ToInt32(Console.Read());
Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
}
} while (stopOrContinueAdding != true) ;
I'm not entirely sure where I went wrong. I'd like to understand more :(
Thanks!
In your addition calculator, changing the following line:
aNum[number - 1] = Convert.ToInt32(Console.Read());
from Console.Read() to Console.ReadLine() seems to fix the issue. ReadLine() will block the execution until Enter is hit - Read() will not... So when you enter your second number and hit Enter, it executes your next ReadLine() statement (where you are expecting "a" or "b" depending on whether they want to continue) as a blank string.

String vector with user input [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Stuck for hours on this task. I really appreciate help, it is not shown in the literature how this is to be done. I can create the vector but after that I'm totally blocked.
Create a string vector with five elements. The user will then enter 5 names via a for loop. The program then writes these names via another for loop.
Please type out the code so I can understand. Without solving this first task I can't do the other ones.
Here's my futile attempt so far
int [] namn = new int [5];
for (int i = 0; i < 5; i++);
{
Console.Write("Ange fem namn");
string str = Console.ReadLine();
int names = Convert.ToInt32(str);
}
It seems that the main (and the most difficult error to find) is ; after for loop
for (int i = 0; i < 5; i++);
this loop does nothing five times.
//DONE: "string[]" - Create a STRING vector with five elements...
string [] namn = new string [5];
//DONE: namn.Length - no magic numbers (5)
for (int i = 0; i < namn.Length; i++) // !!! no ";" !!!
{
Console.Write("Ange fem namn");
//DONE: put into array, not to a local variable
namn[i] = Console.ReadLine();
}
// Print out the names
foreach(var item in namn)
Console.WriteLine(item);

For loop working in C# [closed]

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);

How do you loop Readline statements? [closed]

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 9 years ago.
Improve this question
I have a homework assignment and I am stuck on a certain part of the question.
How do I loop numbers regarding the readline statement.
In other words, suppose I have two numbers that I want to input. Instead of typing out the readline statement twice, how do I get a loop that would allow me to type the readline statement once?
have two numbers that I want to input. Instead of typing out the readline statement twice, how do I get a loop that would allow me to type the readline statement once
Well, if you want two numbers, then you're going to need two variables (or an array), so I assume you're trying to change this:
int firstNumber;
int secondNumber;
firstNumber = int.Parse(Console.ReadLine());
secondNumber = int.Parse(Console.ReadLine());
into something like this:
int[] myNumbers = new int[2];
for(int i = 0; i < 2; i++)
{
myNumbers[i] = int.Parse(Console.ReadLine());
}
but think about this:
Will the prompt be the same for both numbers? Or will the prompt change between inputs
Is it easier to assess the variables independently versus a part of the array/list?
Will having the numbers in a structure benefit other parts of my app (looping to get a sum, etc.)
I think a loop as fine so long as you don't end up with logic inside the lop that changes depending on which number you're using:
int[] myNumbers = new int[2];
for(int i = 0; i < 2; i++)
{
if i == 0 // bad
string prompt = "Enter the first number";
else
string prompt = "Enter the second number";
Console.WriteLine(prompt);
myNumbers[i] = int.Parse(Console.ReadLine());
}
int[] myInputs = new int[2];
for(int i=0; i < 2; ++i)
{
myInputs[i] = Int32.Parse(Console.ReadLine());
}
After this, myInputs[0] is the first value, and myInputs[1] is the second value.

Categories