Im very new to C# and I am trying to complete my assignment but I came across some errors that I don't understand how to fix or even what they are implying.
using System;
public class Assignment1B
{
public static void Main(string[] args)
{
string item_one, itemtwo;
int itemone_quantity, itemtwo_quantity;
float itemone_cost, itemtwo_cost, itemone_total, itemtwo_total;
// Asking first item
Console.Write("What are you buying? ");
item_one = Console.ReadLine();
Console.Write("How many? ");
itemone_quantity = int.Parse(Console.ReadLine());
Console.Write("What do they cost? ");
itemone_cost = float.Parse(Console.ReadLine());
Console.WriteLine();
// Asking second item
Console.Write("What else are you buying? ");
itemtwo = Console.ReadLine();
Console.Write("How many? ");
itemtwo_quantity = int.Parse(Console.ReadLine());
Console.Write("What do they cost? ");
itemtwo_cost = float.Parse(Console.ReadLine());
Console.WriteLine();
// Math
itemone_total = itemone_quantity * (float)itemone_cost;
itemtwo_total = itemtwo_quantity * (float)itemtwo_cost;
// Listing everything
Console.WriteLine("Your list:");
Console.WriteLine("--------");
Console.WriteLine("{0} ({1})", item_one, itemone_quantity);
Console.WriteLine("{0} ({1})", itemone_cost, itemone_total);
Console.WriteLine();
Console.WriteLine("{0} ({1})", itemtwo, itemtwo_quantity);
Console.Write("{0} ({1})", itemtwo_cost, itemtwo_total);
}
}
The assignment wants me to asks you for the name, quantity, and price of two grocery store items. Then display them as a list.
What I have tried:
I have tried looking up the error codes individually to try and see if I can find an example to get a better understanding of why I am getting the error but I haven't found anything that deeply explains everything. Sorry I am still learning and I am open to any advice or tips.
Errors that I have:
item_one = Console.ReadLine(); Warning CS8600: Converting null literal or possible null value to non-nullable type
itemone_quantity = int.Parse(Console.ReadLine()); Warning CS8604: Possible null reference argument for parameter 's' in 'int int.Parse(string s)'.
itemone_cost = float.Parse(Console.ReadLine()); Warning CS8604: Possible null reference argument for parameter 's' in 'float float.Parse(string s)'.
itemtwo = Console.ReadLine(); Warning CS8600: Converting null literal or possible null value to non-nullable type.
itemtwo_quantity = int.Parse(Console.ReadLine()); Warning CS8604: Possible null reference argument for parameter 's' in 'int int.Parse(string s)'.
itemtwo_cost = float.Parse(Console.ReadLine()); Warning CS8604: Possible null reference argument for parameter 's' in 'float float.Parse(string s)'.
You should change the variable names to be more descriptive and related to grocery items, such as itemOneName, itemOneQuantity, itemOnePrice, itemTwoName, itemTwoQuantity, and itemTwoPrice.
In the prompts for item one, use the appropriate variable names instead of "What are you buying?" "How many?", and "What do they cost?"
Similarly, for item two, use the appropriate variable names instead of "What else are you buying?" "How many?", and "What do they cost?".
try changing the output section, change the format to display the list of items in a clearer way, for example:
Console.WriteLine("Your list:");
Console.WriteLine("--------");
Console.WriteLine("Item: {0}, Quantity: {1}, Price: {2}, Total: {3}", itemOneName, itemOneQuantity, itemOnePrice, itemOneQuantity * itemOnePrice);
Console.WriteLine("Item: {0}, Quantity: {1}, Price: {2}, Total: {3}", itemTwoName, itemTwoQuantity, itemTwoPrice, itemTwoQuantity * itemTwoPrice);
something like this in the end?
using System;
public class Assignment1B
{
public static void Main(string[] args)
{
string itemOneName, itemTwoName;
int itemOneQuantity, itemTwoQuantity;
float itemOnePrice, itemTwoPrice, itemOneTotal, itemTwoTotal;
// Asking first item
Console.Write("What is the name of the first item? ");
itemOneName = Console.ReadLine();
Console.Write("How many of {0} do you want? ", itemOneName);
itemOneQuantity = int.Parse(Console.ReadLine());
Console.Write("What is the price of {0}? ", itemOneName);
itemOnePrice = float.Parse(Console.ReadLine());
Console.WriteLine();
// Asking second item
Console.Write("What is the name of the second item? ");
itemTwoName = Console.ReadLine();
Console.Write("How many of {0} do you want? ", itemTwoName);
itemTwoQuantity = int.Parse(Console.ReadLine());
Console.Write("What is the price of {0}? ", itemTwoName);
itemTwoPrice = float.Parse(Console.ReadLine());
Console.WriteLine();
// Math
itemOneTotal = itemOneQuantity * itemOnePrice;
itemTwoTotal = itemTwoQuantity * itemTwoPrice;
// Listing everything
Console.WriteLine("Your list:");
Console.WriteLine("--------");
Console.WriteLine("Item: {0}, Quantity: {1}, Price: {2}, Total: {3}", itemOneName, itemOneQuantity, itemOnePrice, itemOneTotal);
Console.WriteLine("Item: {0}, Quantity: {1}, Price: {2}, Total: {3}", itemTwoName, itemTwoQuantity, itemTwoPrice, itemTwoTotal);
}
}
Related
My coding teacher gave me homework to build b a working code.
So i did and when i ran it it said there was an error. I couldn't find one and neither could my teachet. So my mom recommended to ask here to see if maybe we messed something. Sorry if i have spelling mistakes i am still learning English. P.s. i am learning the language c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Dcoder
{
public class Program
{
public static void Main(string[] args)
{
string sibling1;
string sibling2;
int age_sibling1;
int age_sibling2;
Console.WriteLine( " insert your name and your age " );
sibling1 = string Console.ReadLine();
age_sibling1 = int.Parse(Console.ReadLine());
Console.WriteLine( " insert your sibrlings name and age " );
sibling2 = string Console.ReadLine();
age_sibling2 = int.Parse(console.ReadLine());
if (age_sibling1 > age_sibling2);
Console.WriteLine(sibling1 + " is bigger " );
Else;
if (age_sibling2 > age_sibling1);
Console.WriteLine(sibling2 + " is bigger " );
}
}
}
Made some changes to your code. Some suggestions: Int.Parse will throw an exception if user doesnt enter a number. I would suggest using try/catch
or Int32.TryParse.
Another thing is if you are using variable1, variable2, variable3 etc. its time to create a method and avoid using variableN.
string sibling1, sibling2;
int age_sibling1, age_sibling2;
Console.WriteLine("Insert sibling 1 name ");
sibling1 = Console.ReadLine();
Console.WriteLine("Insert sibling 1 age ");
age_sibling1 = int.Parse(Console.ReadLine());
Console.WriteLine("Insert sibling 2 name ");
sibling2 = Console.ReadLine();
Console.WriteLine("Insert sibling 2 age ");
age_sibling2 = int.Parse(Console.ReadLine());
if (age_sibling1 > age_sibling2)
Console.WriteLine($"{sibling1} is bigger ");
else
Console.WriteLine($"{sibling2} is bigger ");
// Wait for user.
Console.ReadKey();
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 5 years ago.
Improve this question
I am doing my homework. English is not my first language, so I am confused.
This is the question: Write a program that computes the average of five exam scores. Declare and perform a compile-time initialization with the five exam values. Declare integer memory locations for the exam values. Use an integer constant to define the number of scores. Print all scores. The average value should be formatted with two digits to the right of the decimal. Rerun the application with different values. Be sure to desk check your results.
I am not sure what is "a compile-time initialization" mean? What is "Declare integer memory locations for the exam values." want me to do? What is "desk check" mean?
Here is my c# code:
using System;
using static System.Console;
namespace Chap2_1
{
class Chap2_1
{
static void Main()
{
int score1;
int score2;
int score3;
int score4;
int score5;
double average;
Console.Write("Please enter the 1st score: ");
score1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 2nd score: ");
score2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 3rd score: ");
score3 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 4th score: ");
score4 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 5th score: ");
score5 = Convert.ToInt32(Console.ReadLine());
average = (score1+score2+score3+score4+score5) /5;
Console.Write("Average score is " + "{0:N2}", average);
Console.ReadKey();
}
}
}
I am not sure what is "a compile-time initialization" mean?
It means that your scores should have a value set in code from the start (hard coded), rather than values set by user input or "figured out" by the program after it's already running.
In other words, replace this:
Console.Write("Please enter the 1st score: ");
score1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 2nd score: ");
score2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 3rd score: ");
score3 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 4th score: ");
score4 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter the 5th score: ");
score5 = Convert.ToInt32(Console.ReadLine());
With something like this:
//Replace the pointed numbers with whatever the scores should be.
// ||
// vv
score1 = 11;
score2 = 22;
score3 = 33;
score4 = 44;
score5 = 55;
What is "Declare integer memory locations for the exam values."
It means declaring the variables responsible for holding the scores so that you can average them. In other words, this part:
int score1;
int score2;
int score3;
int score4;
int score5;
What is "desk check" mean?
It means that you should average the scores with pen & paper, and make sure the result your program outputs is correct.
PS: I don't want to be rude, but this community is made for questions about code. If you don't understand the question, or english in general, you should ask your teacher.
We are here to help you with programming... not with translation or interpretation.
Shouldn't these be questions for your teacher? Your teacher will know your struggles and be able to help you far better than any of us simply because of his/her role in your studies.
That said, a compile-time initialization is something like:
int[] scores = new int[] { 100,80,90,64,72 };
or:
int score1 = 100;
int score2 = 80;
int score3 = 90;
int score4 = 64;
int score5 = 72;
As far as the memory locations go, I'd recommend reading Microsoft's C# programming guide here about it:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/how-to-obtain-the-address-of-a-variable
Oh, and "desk check" means to do the same calculations manually with pen and paper to validate that you get the same results as your code.
Fill array with user input but not using for loop, because the user need to select when to enter the data.
for loop will not be useful here because I'm not trying to let the user enter all the input at once, but when the user chooses to via switch statement.
I don't know if this makes any sense, new here, excuse my unprofessional language.
static void AddChemical(string[] ChemicalName, string[] Supplier, int[] YearPurchased, int[] Toxicty, int[] Flammability, int[] Corrosiveness, int[] Explosive, int[] Harmful, int[] Overall, float[] Quantity, float[] Cost)
{
int Count = 0;
Count = Count + 1;
Console.Write("Enter the name of the Chemical: ");
ChemicalName[Count] = Console.ReadLine();
Console.Write("Enter the year it was Purchased: ");
int.TryParse(Console.ReadLine(), out YearPurchased[Count]);
Console.Write("Enter the Supplier of the Chemical: ");
Supplier[Count] = Console.ReadLine();
Console.Write("Enter the Quantity of the Chemical in (L/Kg): ");
float.TryParse(Console.ReadLine(), out Quantity[Count]);
Console.Write("Enter the cost of the Chemical: ");
float.TryParse(Console.ReadLine(), out Cost[Count]);
Console.Write("Enter the Toxicty of the Chemical: ");
int.TryParse(Console.ReadLine(), out Toxicty[Count]);
Console.Write("Enter the Flammability of the Chemical: ");
int.TryParse(Console.ReadLine(), out Flammability[Count]);
Console.Write("Enter the Corrosiveness of the chemical: ");
int.TryParse(Console.ReadLine(), out Corrosiveness[Count]);
Console.Write("Enter the Explosive of the Chemical: ");
int.TryParse(Console.ReadLine(), out Explosive[Count]);
Console.Write("Enter the Harmful of the Chemical: ");
int.TryParse(Console.ReadLine(), out Harmful[Count]);
}
This method is inside a switch statement.
I Really Have no idea what you are trying to do, but if you are talking about entering all the inputs into a array but not in the same time you can use collections.
first you need to use the nampspace
using System.Collections
Then Create a new Collection that holds on your results
ArrayList dataHolder = new ArrayList();
Then Whenever you need to add Something to it just type this code
dataHolder.Add("We are adding a string");
dataHolder.Add(21) // Adding a Number
and you can get them letter by index
Console.WriteLine(dataHolder[1]); // Outputs 21
BTW this is really non-efficient way of writing the code but i am just helping you out ;)
I am trying to create a program which calculates the result of exams by taking in the number of marks obtained in each subject. It is almost done but I'm encountering an error that is, if the user just presses enter instead of entering a value, the application wont proceed. Also is there any way to shortening this code?
Console.WriteLine("Danyal's result calculator for students of class IX. Enter the marks requested, if not applicable leave blank and press enter :)");
Console.Write("Enter your Urdu marks: ");
int urdu = int.Parse(Console.ReadLine());
Console.Write("Enter your Maths marks: ");
int maths = int.Parse(Console.ReadLine());
Console.Write("Enter your English Literature marks: ");
int lit = int.Parse(Console.ReadLine());
Console.Write("Enter your Biology marks: ");
int bio = int.Parse(Console.ReadLine());
Console.Write("Enter your Chemistry marks: ");
int chem = int.Parse(Console.ReadLine());
Console.Write("Enter your Islamiat marks: ");
int isl = int.Parse(Console.ReadLine());
Console.Write("Enter your Physics marks: ");
int physics = int.Parse(Console.ReadLine());
Console.Write("Enter your Computer marks: ");
int comp = int.Parse(Console.ReadLine());
Console.Write("Enter your English Language marks: ");
int lang = int.Parse(Console.ReadLine());
Console.Write("Enter your Pakistan Studies marks: ");
int pst = int.Parse(Console.ReadLine());
int total = urdu + maths + lit + lang + bio + chem + physics + isl + comp + pst;
Console.WriteLine("Your total marks are {0} out of 1000", total);
float percentage = total * 100 / 1000;
Console.WriteLine("Your percentage is: {0}%",percentage);
Console.WriteLine("Note: the percentage has been rounded off. Please share this program with other classmates, also I am open to suggestions for creating more helpful programs.");
Console.ReadLine();
I'm not sure what you would want to do in case the user leaves it blank, or enters an invalid value, but you could do something like this.
Dictionary<string,int> grades = new Dictionary<string, int>
{
{ "Urdu", 0 },
{ "Maths", 0 },
{ "English", 0 },
{ "Biology", 0 },
{ "Chemistry", 0 },
{ "Islamiat", 0 },
{ "Physics", 0 },
{ "Computer", 0 },
{ "English Language", 0 },
{ "Pakistan Studies", 0 },
};
foreach (string grade in grades.Keys.ToArray())
{
Console.WriteLine(string.Format("Enter your {0} marks: ", grade));
int mark;
if (int.TryParse(Console.ReadLine(), out mark))
grades[grade] = mark;
}
int total = grades.Sum((g) => g.Value);
In this example, if bad input is used the grade will default to 0. If you wanted to you could change the if try parse to a loop and request a good value until one is entered as well.
This is a clear case of not adhering to the DRY principle. You are repeating operations that are essentially the same, don't do that. Refactor the code so that common patterns or behaviors are solved in one single place.
How would you do that here?
Create a method that prompts the user to enter certain information. What does the user need? A descriptive message of what he has to do. What does the user need to do? Enter a valid input. Ok, with that in mind, the following prototype of a method seems like a good starting point:
private static int GetUserInput(string message) { ... }
Hmmm...enter a valid input. This means we need some sort of validation, so again let's think of how we can solve this:
private static int ValidateUserInput(string input) { ... }
Is this good enough? Well...no quite. What happens if the user enters an incorrect number? There is no convenient way of conveying that the input is not valid to the caller. We could return -1, or we could throw an exception, but both seem offish.
The best solution would be to return two values; one telling us if the input is valid and another telling us what the input is. In c# this isn't very striaghtforward (at least until c# 7 comes along). The way to do it is using out arguments:
private static bool ValidateUserInput(string message, out int input) { ... }
Now this method serves our purpose perfectly. The return value tells us if the input is valid and the out argument input gives us the validated value (or we simply ignore it if the validation failed).
Why are you creating an int variable for each mark if you essentially only want sums and averages? Lets create a List<int> where we store all the marks.
Another option, if you want to keep track of what mark corresponds to what subject, would be to use a Dictionary<string, key> where the key would be the subject name and the value its corresponding mark. But lets use List<int> for now.
With all that in mind we can build up our solution:
public static void ComputeMarksSummary()
{
var marks = new List<int>();
marks.Add(GetUserInput("Enter your Urdu marks: "));
marks.Add(GetUserInput("Enter your Maths marks: : "));
marks.Add(GetUserInput("Enter your English Literature marks: "));
marks.Add(GetUserInput("Enter your Biology marks: "));
marks.Add(GetUserInput("Enter your Chemistry marks: "));
marks.Add(GetUserInput("Enter your Islamiat marks: "));
marks.Add(GetUserInput("Enter your Computer marks: "));
marks.Add(GetUserInput("Enter your English language marks: "));
marks.Add(GetUserInput("Enter your Pakistan studies marks: "));
var total = marks.Sum();
Console.WriteLine("Your total marks are {0} out of 1000", total);
Console.WriteLine("Your percentage is: {0}%", total/10.0); //note the 10.0 to force double division, not integer division where 44/10 would be 4 not 4.4
Console.WriteLine("Note: the percentage has been rounded off. Please share this program with other classmates, also I am open to suggestions for creating more helpful programs.");
//WRONG! Percentage is not rounded off, its truncated: 9/10 is 0 in integer division.
Console.ReadLine();
}
private static int GetUserInput(string message)
{
int mark;
while (true)
{
Console.WriteLine(message);
var input = Console.ReadLine();
if (!ValidateUserInput(input, out mark))
{
Console.WriteLine("Invalid input, please try again.");
}
else
{
return mark;
}
}
}
private static bool ValidateUserInput(string message, out int input)
{
//left as an excerice. Hint: look into int.TryParse(...);
//here you could decide if a blank input should be valid and parsed as zero.
}
Wow, now that seems a lot cleaner....but hey, we can still do a little bit better. Whats up with all those marks.Add(....)? Can't we refactor the code some more? Well yes, we are essentially asking always the same thing, only the subject name changes. How about we do something like this:
public static void ComputeMarksSummary(IEnumerable<string> subjectNames)
{
var marks = new List<int>();
foreach (var subject in sujectNames)
{
marks.Add(GetUserInput(string.Format("Enter your {0} marks: ", subject)));
}
var total = marks.Sum();
Console.WriteLine("Your total marks are {0} out of 1000", total);
Console.WriteLine("Your percentage is: {0}%", total/10.0); //note the 10.0 to force double division, not integer division where 44/10 would be 4 not 4.4
Console.WriteLine("Note: the percentage has been rounded off. Please share this program with other classmates, also I am open to suggestions for creating more helpful programs.");
Console.ReadLine();
}
And you could call it like this:
ComputeMarksSummary(new string[] { "Urdu", "Maths", ... );
Doesn't that seem so much cleaner?
When I used {0} in following code:
class Program
{
double width;
double height;
public void getData() {
Console.WriteLine("Enter Width:");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Height:");
height = Convert.ToDouble(Console.ReadLine());
}
public double calcArea() {
return width * height;
}
public void display() {
Console.WriteLine("Area is : {0}",calcArea());
}
}
class Area
{
static void Main(string[] args)
{
Program p = new Program();
p.getData();
p.display();
}
}
The output was:
Enter Width:6Enter Height:9Area is : 54
And when I used {0} in this:
class NewArea
{
static void Main(String[] args) {
double width;
double height;
double area;
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Height: ");
height = Convert.ToDouble(Console.ReadLine());
area = width * height;
Console.WriteLine("Area is: {0}" +area);
}
}
The output was
Enter Width:4Enter Height:5Area is: {0}20
What does {0} mean?
There are two different meaning for {0} as you have used.
Console.WriteLine("Area is : {0}",calcArea());
In above sentence once you give {0} it means that you may provide some value after comma in same sentence as you provide the value 54 after comma so Console figured that and place that value at 0.
In similar way you can provide many values like
Console.WriteLine("Area for Width {0} and Height {1} is {2}",
width, height, calcArea());
OutPut: Area for Width 4 and Height 5 is 20
In another line you used it like
Console.WriteLine("Area is: {0}" +area);
As in this statement format did not find any comma after {0}" instead found + area so it replace varibale area with value and printed {0} as there is not any matching value {0} which should be given after comma like earlier statement.
It's a placeholder for the matching parameter in String.Format and WriteLine
For example:
String.Format("My name is {0} and I love {1}!", "Orel Eraki", "Snooker");
Output:
My name is Orel Eraki and I love Snooker!
String.Format(String,Object[])
The String argument obviously takes your string, then you can insert multiple object values although this is not necessary. The {0} is just a way to signify that the value of the first object argument will be placed there, similarly {1} means the second and {2} the third. It uses array index syntax.
if you write:
String.Format("Value = {0}",val);
and val is an integer with the value of 20 then the output will be:
'Value=20'
but if you write
String.Format("Value = {0}"+val)
then you are not giving two arguments to the method but only one, a concatenated string that consists of the "Value= {0}" string and the return value of the ToString() method of val.
Since there is no second argument the {0} is treated as just a part of the string and not as something with special meaning. That's why the output is: Value = {0}20
It injects the returning value of calcArea() into the string before printing it on the console window
If you use more than one parameter, you need to use {1}, {2}, etc. You might also use one parameter in more than one place by specifying e.g. {0} more than once.
Just see the example below,
static void Main()
{
int a=10;
int b=20;
Console.WriteLine(" The value of A is {0} " ,a);
Console.WriteLine(" The value of A is {0}, the Value of B is {1}",a,b);
Console.Read();
}
see the first WriteLine statement, i'm printing A alone. {0} is the place my printing variable will be seen in output. The same way i have written the second statement with two outputs {0}, {1} So it will be printed accordingly.