I am attempting to write a C# program (in visual studio) that takes some numbers as keyboard input and prints which of them is the smallest and largest. This is a homework assignment and I intend to use only the things covered in the class up to this point. So, I am quite aware that this could be done in a much simpler way with an array and the MATH.min and max methods. However, the point of this program is just to practice if/else logic. Anyway, the logic is not my issue. The code below works as intended until the final user entered number is input, then it just closes without printing the final writeline statement used to show the results. Is there something that needs to be done to fix this? Thanks!
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
double maxNum = 0;
double minNum = int.MaxValue;
int numToEnter;
int enterCounter = 0;
double currentNum;
Console.Write("How many numbers will be entered?: ");
numToEnter = int.Parse(Console.ReadLine());
while (enterCounter < numToEnter)
{
Console.Write("Enter a positive number: ");
currentNum = double.Parse(Console.ReadLine());
if (currentNum >= 0)
{
if (currentNum >= maxNum)
{
maxNum = currentNum;
}
if (currentNum < minNum)
{
minNum = currentNum;
}
enterCounter++;
}
else
{
Console.Write("Please enter a positive number: ");
}
}
Console.WriteLine("The largest number is: {0}. The lowest number is: {1}", maxNum, minNum);
}
}
}
Your issue is likely related to the way that you're testing the program. I can't be sure but one way to fix it is by using this at the end of your main.
Console.ReadLine();
Are you running it w/ debugging or without debugging? I suspect you're running with debugging which would explain why it's happening. There is a difference between "Start with debugging" and "Start without" generally speaking with debugging will terminate the application immediately however a "Release Build" will not. So you can use either Console.ReadLine() method to stop it but if your instructor requires a release build then your code is fine.
F5 = Run With Debugging
CTRL + F5 = Run Without Debugging (Used for Release Builds) or if you don't know how to use breakpoints.
Personally I recommend using a for loop with this instance.
for (enterCounter; enterCounter <= numToEnter; enterCounter++)
{
//Run This code
}
Add
Console.ReadLine();
After
Console.WriteLine("The largest number is: {0}. The lowest number is: {1}", maxNum, minNum);
Related
I am confused. When I write the following code, and start the program up, it just shows a blank output. I read online what the problem could be and the most people seem to agree that it's a problem in my code after all, but I cant see where I messed up:
sorry forgot to put the details guys. This is the assignment and the different input/outputs etc:
You and your colleagues are huge fans of your local football team. You therefore often show up to support your team. When your team has made at least ten perfect passes to each other, you give each other one "high five" and "cheers". At more than one and up to ten passes, cheer in "huh!" for each delivery. If your team scores a goal break out in "Olé olé olé". If you have zero submissions, you are silent and say "Shhh". Your boss is so excited about the way you support your team. Therefore you will be tasked to make a program that can run your logic, so that other colleagues can join next time there is local showdown.
TASK
Based on the number of passes played, which your local team has managed, the following applies:
• "High Five - Cheers!!!" for 10 submissions and above,
• "Shh" for less than 1 delivery
• or a string that has "Huh!" for each pass played.
• If your dream team scores a goal, print ONLY "Olé olé olé".
Requirements for Input
The program takes two inputs, an int and string value. The first value represents number submissions and the next value takes the text "target" as input value.
Targets must be able to be written in CAPITAL or lowercase letters, or in one or more capital and small letters letters.
Output
A string that suits your cheering level
Ex 1 on input
5
Goal
Ex 1 on output
Olé olé olé
Ex 2 on input
3
string.Empty;
Ex 2 on output
Huh! Huh! Huh!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProjectFodbold
{
internal class Program
{
static void Main(string[] args)
{
int i = 1;
int Passes = Convert.ToInt32(Console.ReadLine());
string GoalCheck = Console.ReadLine();
string Goal = "Goal";
string Output1;
if (Goal.Equals(GoalCheck, StringComparison.OrdinalIgnoreCase) == true)
{
Console.WriteLine("Olé olé olé");
}
else if (Passes == 0)
{
Console.WriteLine("Shhh.");
}
else if (Passes > 9)
{
Console.WriteLine("High Five - Cheers!!!");
}
else
{
Output1 = "Huh! ";
while (i < Passes)
{
Output1 = Output1 + "Huh! ";
i = i + 1;
}
Console.ReadLine();
}
}
}
}
Hope someone can give me some insight on this problem
I have tried looking for the problem but no luck
The implementation is not very solid, but i can see you are in the learning phase, so here there are some comments:
I would strongly recommend avoiding Convert without having a try catch because it can generate an exception if the input is not correct, so i would do something like this:
bool isInputValid = int.TryParse(Console.ReadLine(), out int Passes);
And after that it would be great if you validate the inputs from your user, using some extra logic.
The problem with your implementation is that it is not clear what is required, so i suggest to write to the console some help messages:
Console.WriteLine("Insert number of Passes");
bool isInputValid = int.TryParse(Console.ReadLine(), out int Passes);
Console.WriteLine("Write goal Check");
string GoalCheck = Console.ReadLine();
And delete the Console.ReadLine() after your While loop, instead just write it in the last line of your code.
I am new to Kattis and trying solve the challenge Jumbo Javelin with C# but I get run time error even though I am exiting my program with 0.
Here is my code:
using System;
namespace JumboJavelin
{
class Program
{
static void Main(string[] args)
{
int l = int.Parse(Console.ReadLine());
int sum = 0;
int loss = 1;
for (int n = 0; n <= 100; n++)
{
sum += l;
if((n + 1) % 2 == 0 && !n.Equals(0))
{
sum -= ((n + 1) / 2)*loss;
}
try
{
l = int.Parse(Console.ReadLine());
}
catch (FormatException)
{
break;
}
}
Console.WriteLine(sum);
Environment.Exit(0);
}
}
}
Can someone please help me? I know my solution eventually outputs the wrong answer but right now I am trying to get rid of the run time error since it works perfectly fine on Visual Studio 2019.
All help is appreciated. Thanks
If you change the error your catch to Exception you will see that it is actually a wrong answer, so something goes wrong. You do exit your program with an exit code 0 at the bottom of your code, however, it throws an Exception somewhere else. Two things to consider:
First, the problem statement explains that as a first input, you get an integer N (this N indicates the amount of steel rods he has) and CAN BE between 1 and 100 (1 not inclusive hence, 1<N<=100). You now have a loop that always loops from 1 to 100. And the loop should loop from 1 up to and including whatever value N is. Try to see what you can do about that.
Second you read the input at the "tail" of the loop. This means that after the last cycle you do another read input. And that you do not read the first l. Try changing reading the input for l at the beginning of the loop. (and the first input you read in your Main, should not be for l (see point 1)).
See how far this gets you, is something is not clear please let me know.
As Kasper pointed out, n is dynamically provided on the first line; don't assume you have 100 lines to collect with for (int n = 0; n <= 100; n++).
There's no need to handle errors with the format; Kattis will always adhere to the format they specify. If something goes wrong parsing their input, there's no point trying to catch it; it's up to you to fix the misunderstanding. It's better to crash instead of catch so that you won't be fooled by Kattis telling you the failure was due to a wrong answer.
A simple approach is as follows:
Collect n from the first line of input; this is the preamble
Loop from 0 to n, collecting each line
Accumulate the values per line into a sum
Print sum - n + 1, the formula you can derive from their samples
using System;
class JumboJavelin
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += int.Parse(Console.ReadLine());
}
Console.WriteLine(sum - n + 1);
}
}
You can use this pattern on other problems. You won't always aggregate one result after n lines of input though; sometimes the input is a single line or you have to print something per test case. Some problems require you to split and parse each line on a delimiter.
Regardless of the case, focus on gathering input cleanly as a separate step from solving the problem; only combine the two if you're confident you can do it without confusion or if your solution is exceeding the time limit and you're sure it's correct otherwise.
While loops runs through the if statement once and stops.
I am new to c#, so excuse me if I am overlooking something seemingly obvious. I am currently writing a program that visualizes the Collatz conjecture through console entries. The program begins by prompting the user to enter a natural number. The program is supposed to run that number through the formulae of the conjecture until it eventually reaches a value of 1. However, when I type in the number in console, the program runs it through one formula and crashes. It seems that is has a problem with the Double.Parse line. I already tried using the convert method and tried defining "num" as a decimal instead of a double.
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
{
if (num % 2 == 0)
{
Console.WriteLine(num / 2);
num = Double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine(num * 3 + 1);
num = Double.Parse(Console.ReadLine());
}
}
Console.ReadLine();
}
}
}
}
To be honest, I'm not positive what you're trying to achieve from the description (i.e., I have not idea what a Collatz conjecture visualization formula is), but I think I figured out what your issue is.
I think you're a little confused about Console.ReadLine(). This method pauses and waits for user input. As a result, during your first loop through the while statement, your program will pause and wait for user input. I think what you're trying to do is take the result of the formula in either the "if" or "else" section and capture that as the new value of "num."
Here is my best guess at what you're trying to achieve:
static void Main(string[] args)
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
Console.WriteLine(num);
}
else
{
num = num * 3 + 1;
Console.WriteLine(num);
}
}
Console.WriteLine(num);
Console.ReadLine();
}
Also, it looks like you might have an extra set of brackets within your while statement. It doesn't seem like that would compile as-is, so perhaps it is just the way in which you copied it into your question.
The only thing showing up is "press enter to continue". Ive tried switching the debug settings around but nothing is working. None of my writeline codes are outputting anything. The language is c#
Console.WriteLine("enter the values of sales");
int sales;
int commission = new int();
String value = Console.ReadLine();
if (int.TryParse(value, out sales))
if (sales < 100000)
commission = 5;
else if (sales >= 100000 && sales <= 250000)
commission = 6;
else if (sales >= 250000)
commission = 7;
else
{
Console.Write("sales");
Console.WriteLine(sales);
sum = sum + ((sales / 100) * (commission));
i--;
return;
}
else
{
Console.WriteLine("total of all commissions");
Console.Write(sum);
return;
}
}
Console.WriteLine etc. are indeed correct ways to output something to the console window, so they should produce output if and when executed.
What you SHOULDN'T be seeing is a message "press enter to continue" - because that simply isn't in the code you posted, and is no default behaviour of console applications either.
Which leads me to the conclusion that your code isn't executed at all. You could easily test this by setting a breakpoint at the beginning of your code, and see if that breakpoint is reached at all (visual studio would stop and wait for you to click on continue when reaching a breakpoint).
Are you sure that A) you are actually compiling & launching your application from visual studio (not just opening some .exe from the explorer), and B) that your code is placed in your application's main method? By default, that would be ...
class Program
{
static void Main(string[] args)
{
// right in here!
}
}
According to your conditions, your code will never reach the Console.Write("sales") because you test all possible values of sales before the else cause.
The only two places it has any printing, it's when:
TryParse worked: Printing doesn't work.
TryParse didn't worked: Printing OK.
We can examine and see that #1 printing appears at the else which is completely dependent upon sales value.
When we examine the conditions before the **else, we can see they are handling the entire range of possible numbers.
(sales < 100000)
(sales >= 100000 && sales <= 250000)
(sales >= 250000)
Else - Never can be reached.
Thus, you should rethink which operations goes when, and if the else is even need, and if it does, in which range it should apply.
Note: You have twice the handling on "250000" 2nd and 3rd conditions, but because 2nd condition comes first, it will only apply for it, thus the 3rd condition is redundant = and should be removed. (Or move the equality for the 3rd condition.)
I have checked a bunch of places with very minimal help to help me figure out a methods way in visual studios to open up the console when running the code to prompt the user from the Console.Writeline("Please enter seconds to convert: "); to input the number of seconds that they are trying to convert, once thats put in it would then print the results of the conversion as "Your result is 00:00:00" . Im still in the process of learning more about c# so i have one slightly basic understanding so far and a basic solution but what i currently have is not that I'm trying to have for this project. My solution so far is :
class Program
{
static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(36100556);
Console.WriteLine(t.Days);
Console.WriteLine(t.Hours);
Console.WriteLine(t.Minutes);
Console.WriteLine(t.Seconds);
Console.WriteLine(t.ToString());
}
}
I think you need to follow these steps:
1) Send the message requesting the time with the Console.WriteLine.
2) Use the command Console.ReadLine, this will make the console to wait until the user puts the time that need to convert.
3) Read the value and make the math.
4) Display the value using WriteLine.
5) After display the value, put another Consol.ReadLine in order to avoid the console to hide before the user reads the result.
Hope it helps
Console.WriteLine("Enter number of seconds:");
double sec = 0;
// Check if user input correct integer
while(!double.TryParse(Console.ReadLine(),out sec))
{
Console.WriteLine("Your data is invalid. Please input again:");
}
TimeSpan t = TimeSpan.FromSeconds(sec);
Console.WriteLine("Your result is " + t.ToString(#"hh\:mm\:ss"));
Console.ReadLine();
You can use var x = Console.ReadLine() to read input from the console. May have to do some conversions since it will read a string of characters. You can utilize something like Convert.ToDateTime(x) or something to convert to whatever data type you need.
Console.Write("Enter Number of Seconds: ");
string SecondsStr = Console.ReadLine();
Double Seconds = 0;
if(!Double.TryParse(SecondsStr, out Seconds))
{
Console.WriteLine("Invalid number entered");
}
else
{
TimeSpan Time = TimeSpan.FromSeconds(Seconds);
Console.WriteLine(string.Format("Days: {0}, Hours: {1}, Minutes: {2}, Seconds: {3}", Time.Days, Time.Hours, Time.Minutes, Time.Seconds));
}