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.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to C# and programming and currently working on a project by the name of Marshals Revenue. I have an error when I run the program if someone can please help me understand the issue.
It tells me unreachable code detected in regards to the "if" statement (error CS0162) and it won't let me run the processing portion of the code. I'm not sure why I'm receiving the error because it looks like the correct syntax.
I also am told that they want to include the " CultureInfo.GetCultureInfo" method. and the correct format is " WriteLine("This is an example: {0}", value.ToString("C", CultureInfo.GetCultureInfo("en-US")));". I'm not sure if that has something to do with why it wont run my "if" statement and not sure where to put the get culture method statement.
Below is the the code I'm using.
Thanks in advance.
using System;
using System.Globalization;
class MarshallsRevenue
{
static void Main()
{
const int INTERIORPRICE= 500;
const int EXTERIORPRICE=750;
string entryString;
int numberInterior;
int numberExterior;
int revenueInterior;
int revenueExterior;
int total;
bool isInteriorGreater;
// declare the required variables
bool valid;
valid=true;
int Month;
int monthInterPrice=INTERIORPRICE;
int monthExterPrice=EXTERIORPRICE;
// Prompt the user to Enter the month
Console.WriteLine("Enter the number of month being scheduled >>");
// Read the input
entryString = Console.ReadLine();
// convert the input to an integer
Month = Convert.ToInt32(entryString);
Console.WriteLine("Enter number of interior murals being scheduled >>");
entryString = Console.ReadLine();
numberInterior = Convert.ToInt32(entryString);
Console.WriteLine("Enter number of exterior murals scheduled >>");
entryString = Console.ReadLine();
numberExterior = Convert.ToInt32(entryString);
//use a switch case to perform the aciton
//as per the entered month
switch(Month) {
//set the exterior murals
//to zero for the month
//December through February
case 1:
case 2:
case 12:
numberExterior=0;
break;
//if the month is either
//one of April, May, September
//or October, reduce the price
//of exterior murals.
case 4:
case 5:
case 9:
case 10:
monthExterPrice = 699;
break;
//if the month is either
//July or August
//or October, reduce the price
//of interior murals.
case 7:
case 8:
monthInterPrice = 450;
break;
//Do nothing for the months
//of March June and November.
case 3:
case 6:
case 11:
break;
//if the entered month is invalid,
//display an error message and
//set the is valid month to false.
default:
Console.WriteLine("The entered month is invalid.");
valid=false;
break;
//if the entered month is valid
//perform the calculations and display
//the results.
if(valid)
{
revenueInterior = numberInterior * monthInterPrice;
revenueExterior = numberExterior * monthExterPrice;
total = revenueExterior + revenueInterior;
isInteriorGreater = numberInterior > numberExterior;
Console.WriteLine("{0} interior murals are scheduled at {1} each for a total of {2}", numberInterior, monthInterPrice.ToString("C"), revenueInterior.ToString("C"));
Console.WriteLine("{0} exterior murals are scheduled at {1} each for a total of {2}", numberExterior, monthExterPrice.ToString("C"), revenueExterior.ToString("C"));
Console.WriteLine("Total revenue expected is {0}", total.ToString("C"));
Console.WriteLine("It is {0} that there are more interior murals sceduled than exterior ones.", isInteriorGreater);
}
}
}
}
The if statement is unreachable because it is enclosed in the switch statement's braces but is is not a part of any of the cases.
I believe you need:
switch(Month) {
//cases go here
}
if(valid)
{
//if stuff goes here
}
2 things you may want to consider.
you can write bool valid = true;
For the months where you do nothing, you can simply omit the cases.
Move the if statment inside default or like i think is your intention out the switch statment, because any code after the break keyword is ignored
You are using if statement inside the switch. the switch works on cases. it checks for the case value and there is break after each case. so there will be no case your code will execute the if statement.
So if you want to execute the if statement always then move it out of the switch.
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() != "");
}
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.
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 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.
I am attempting to write code (in visual studio 2012 using c#) that will allow a user to select an account using 1,2,3 or 4. i am using a do-while loop so i can use 0 to exit (break?) or run the loop again until a valid option is selected.
The problem is, Visual studio is telling me the code validAccount = true; is unreachable, and won't let me test it. since this method should also return a value i have a "not all code paths return a value" error, and i am getting really confused. here is my code:
static int chooseAccount() {
bool validAccount = false;
do {
Console.Clear();
Console.WriteLine("Select an Account: \r\n 1: Savings \r\n 2: Debit \r\n 3: Credit \r\n 4: Investment");
int inputNumber = int.Parse(Console.ReadLine()); //by declaring int inputNumber here we save having an extra line.
if ((inputNumber >= 1) && (inputNumber <= 4)) {
return inputNumber;
validAccount = true;
}
else if (inputNumber == 0) {
break;
}
else {
Console.WriteLine("Error: please choose an account using 1, 2, 3, 4 or 0 to exit");
}
} while (!validAccount);
}//end chooseAccount
Maybe I've just been staring at this for too long and can't see the simple mistake I've made. I welcome a fresh perspective or direction to where i can find a solution, should this sort of problem have already been solved. (it's kinda hard to google for something like "unreachable code" when the code has to be so specific...)
The line with the error comes right after a return statement. Your code would, in every single case (and the compiler knows this), exit the function on the line before it, so it will never reach the next line.
You don't need to set validAccount to true to break the loop, because the return statement will exit the function, and therefore automatically exit the loop.
And finally, if you set validAccount to true and THEN return, no other function can access validAccount, so why did you need to bother setting it to true?
In truth, you don't need validAccount at all, because with your break and return statements you already control your way in and out of the loop. This will work:
static int chooseAccount() {
while(true) {
Console.Clear();
Console.WriteLine("Select an Account: \r\n 1: Savings \r\n 2: Debit \r\n 3: Credit \r\n 4: Investment");
int inputNumber = int.Parse(Console.ReadLine());
if ((inputNumber >= 0) && (inputNumber <= 4)) {
return inputNumber;
}
else
{
Console.WriteLine("Error: please choose an account using 1, 2, 3, 4 or 0 to exit");
}
}
}
Please be aware that the return statement will take you out of the function immediately. Then the next validAccount = true; will never be executed!
Switch these two:
return inputNumber;
validAccount = true;