It doesn't throw an error on invalid input - c#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KKRIT
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Здравствуйте! Выберите страницу (от 1 до 354):");
string page = Console.ReadLine();
int result = Int32.Parse(page);
while (page <= 1 || page >= 354)
{
Console.WriteLine("Страница введена успешно");
else
{
Console.WriteLine("Такой страницы не существует");
}
}
Console.WriteLine("Переходим на страницу {0}...", page);
Console.ReadLine();
}
}
}
If the input is incorrect, the else text is not displayed
I have already tried all the options from the Internet, repeated the format, but nothing comes out

Your if statements is not right. It should check if page is above or equal to 1 AND below or equal to 354 (Then page is existing).
static void Main(string[] args)
{
Console.WriteLine("Здравствуйте! Выберите страницу (от 1 до 354):");
string page = Console.ReadLine();
int result = Int32.Parse(page);
if (result >= 1 && result <= 354)
{
Console.WriteLine("Страница введена успешно");
}
else
{
// Invalid page
Console.WriteLine("Такой страницы не существует");
}
Console.WriteLine("Переходим на страницу {0}...", page);
Console.ReadLine();
}
You could switch the if statement and check if page is below 1 OR above 354 and then print Invalid page
if (result < 1 || result > 354)
{
// Invalid page
Console.WriteLine("Такой страницы не существует");
}
else
{
Console.WriteLine("Страница введена успешно");
}

Related

NullReferenceException? Why? [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 last year.
Improve this question
I try to calculate the total collective age of my passengers in calc_total_age() this works before I add a passenger and writes out "0". However when I add a passenger I get NullReferenceException, I have tried different things but I just can't wrap my head around what I'm doing. I need a little shove in the right direction and maybe and explanation of what the he** I am doing and I don't know what my GetAge() does either really I have tried to call it but it doesn't seem to work.
This is all my code:
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program {
public static void Main (string[] args) {
//Console.Clear();
Console.WriteLine("Hi, welcome to the Buss-Simulator!");
Console.ReadKey();
var mybus = new Bus();
mybus.Run();
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Bus {
public int total_passengers = 0;
public Passenger[] info_passengers;
public int totalAge = 0;
public int totalSeats = 25;
public void Run()
{
info_passengers = new Passenger[25];
string [] menu = new string[]{"1. Pick up passenger.", "2. Show who's on the bus.", "3. Calculate total age of passengers"};
int MenuSelect = 0;
while (true)
{
Console.Clear();
Console.WriteLine("What do you want to do?");
Console.WriteLine();
Console.CursorVisible = false;
if (MenuSelect == 0)
{
Console.WriteLine(menu[0] + " ⭅");
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 1)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1] + " ⭅");
Console.WriteLine(menu[2]);
}
else if(MenuSelect == 2)
{
Console.WriteLine(menu[0]);
Console.WriteLine(menu[1]);
Console.WriteLine(menu[2] + " ⭅");
}
var keyPressed = Console.ReadKey();
if(keyPressed.Key == ConsoleKey.DownArrow && MenuSelect != menu.Length -1)
{
MenuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && MenuSelect >= 1)
{
MenuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (MenuSelect)
{
case 0:
add_passengers();
break;
case 1:
print_passengers();
break;
case 2:
calc_total_age();
break;
}
}
}
}
public void add_passengers()
{
if (total_passengers == 25)
{
Console.WriteLine("\nBus is full!");
System.Threading.Thread.Sleep(2000);
return;
}
try
{
Console.WriteLine("\nType the name, age & gender of your passenger.");
Console.Write("\nName: ");
string name = Console.ReadLine();
Console.Write("\nAge: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("\nGender: ");
string gender = Console.ReadLine();
Passenger passenger = new Passenger(aName: name, aAge: age, aGender: gender);
Array.Resize(ref info_passengers, info_passengers.Length + 1);
info_passengers[info_passengers.Length - 1] = passenger;
}
catch (Exception e)
{
Console.WriteLine("\nFollow instructions.");
System.Threading.Thread.Sleep(2000);
return;
}
total_passengers++;
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
System.Threading.Thread.Sleep(2000);
return;
}
public void print_passengers()
{
Console.WriteLine();
foreach (var i in info_passengers)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
public void calc_total_age()
{
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
Console.WriteLine(totalAge);
Console.ReadKey();
}
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
class Passenger{
public string name;
public int age;
public string gender;
public Passenger(string aName, int aAge, string aGender)
{
name = aName;
age = aAge;
gender = aGender;
}
public override string ToString()
{
return string.Format($"This is {name}, {gender}, {age} years old.");
}
public int GetAge()
{
return age;
}
}
you don't need to resize info_passengers array since it is enough for total passangers. When you add an extra array cell, you add a passanger to the end of arry, but you still have the empty cells in the beginnig of array with null that are causing the exception.
so remove this code
Array.Resize(ref info_passengers, info_passengers.Length + 1);
and fix this
total_passengers++;
info_passengers[ total_passengers-1] = passenger;
and don't forget to remove total_passengers++; from here
Console.WriteLine("You boarded 1 Passenger." + "\nThere are " + (totalSeats - total_passengers) + " seats left.");
and add totalAge=0 in calc_total_age
public void calc_total_age()
{
totalAge=0;
for (int i = 0; i < total_passengers; i++)
{
totalAge += info_passengers[i].age;
}
and it is not a very good idea to hide errors in your catch blok. I would make it
catch (Exception e)
{
Console.WriteLine("\n Error!!! " + e.Message);
System.Threading.Thread.Sleep(2000);
return;
}
The answer to this one is very simple!
You declare:
public Passenger[] info_passengers;
This actually creates a pointer to a Passenger array, which (like all pointers) is initially null. It does not create the actual array itself.
When your code comes to call:
Array.Resize(ref info_passengers, info_passengers.Length + 1);
the method Resize expects the array parameter to point to an array. However, info_passengers is still null. So you get the exception.
I think all you need to do is to initialise info_passengers to an new empty array, like this:
public Passenger[] info_passengers = new Passenger[]();
and then I think it'll all work.

How can i fix my beginner if and else code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyFirstTest
{
class Program
{
static void Main(string[] args)
{
Int32 value = 57;
if (value < 10)
Console.WriteLine("Value is less than 10");
else (value = 57)
Console.WriteLine("Value is 57!");
else
Console.WriteLine("Value is greater than 10");
Console.ReadLine();
}
}
}
I am a complete beginner and have just started learning C#. I have tried to create a snippet of code using the if and else statements.
When it gets to the below, it throws me some squiggly lines and expects { }.
else (value = 57)
Console.WriteLine("Value is 57!");`
How can i go about fixing this? An explanation would also be great to help a beginner! Thank you in advance.
Firstly you are using if...else if...else Statement, rather than using else for the second time, you have to use else if as you are checking like if the first condition is true, if not true then else if, second condition is true then at last we use else, if any of the above mentioned conditions are not true.
Secondly, to compare, we use == not =
So here your code goes like
if(value < 10)
{
Console.WriteLine("Value is less than 10");
}
else if(value == 57)
{
Console.WriteLine("Value is 57!");
}
else
{
Console.WriteLine("Value is greater than 10");
}
For more information see control statements at https://www.tutorialspoint.com/csharp/if_else_statement_in_csharp.htm
namespace MyFirstTest
{
class Program
{
static void Main(string[] args)
{
Int32 value = 57;
if (value < 10)
{
Console.WriteLine("Value is less than 10");
}
else if(value == 57)
{
Console.WriteLine("Value is 57!");
}
else
{
Console.WriteLine("Value is greater than 10");
}
Console.ReadLine();
}
}
}

C# Console.WriteLine not printing in one line

Now if you run this it does not output each Console.WriteLine in one line, why?
I know console.writeline goes to next line when done but the problem is it jumps to next line while printing when it print the exception var it is not in the same line as the rest of the writeline
The error occurs inside the Display() function at the number 6 variable (exception) it is not in the same line as the rest of the writeline, why?
And also there are no line breaks where the error ocurs.
Ans can be any number you like.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace EquationSolver
{
class Program
{
public static string exception = "No Solution Found yet";
public static int go = 40;
public static Decimal x = 0, formul = 0;
public static Decimal pref = -100000, next = 100000,ans;
public static Decimal stepval = next / 10;
public static Decimal prefrem = 1234567890123.1234567890m, nextrem = 1234567890123.1234567890m;
public static Decimal nextremfirst = 0;
public static void Answer()
{
Console.WriteLine("Enter ans");
ans = (Convert.ToDecimal(Console.ReadLine()));
}
public static void Main(string[] args)
{
//Console.WriteLine("Enter ans");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
//Console.Clear();
while (true)
{
for (var i = 0; i <= go; i++)
{
for (x = pref; x <= next; x += stepval)
{
formul = x;
if (formul < ans)
prefrem = x;
else if (formul > ans)
{
if (nextremfirst == 0)
{
nextrem = x;
nextremfirst += 2;
}
}
else if (formul == ans)
{
AnsFound();
break;
}
else
{
Error();
}
Display();
}
if (formul == ans)
{
AnsFound();
break;
}
if (prefrem != 1234567890123.1234567890m)
pref = prefrem;
if (nextrem != 1234567890123.1234567890m)
next = nextrem;
nextremfirst = 0;
stepval /= 10;
if (formul != ans)
NoAnsyet();
//Console.WriteLine();
}
Finnish();
}
}
public static void Display()
{
//Console.ReadKey();
//Console.WriteLine("Formul: {0} x: {1} Ans: {2} Status: {3}", //formul, x, ans, exception);
//Here is the error:
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",pref,next,stepval,formul,x,ans,exception);
}
public static void Finnish()
{
if (formul != ans)
Error();
exception = "\ncomplete";
Console.WriteLine(exception);
pref = -100000;
next = 100000;
stepval = next /= 10;
Console.ReadKey();
Console.Clear();
//Console.WriteLine("Enter ans:");
//Answer(Convert.ToDecimal(Console.ReadLine()));
Answer();
}
public static void AnsFound()
{
exception = "\nSolution Found!";
//Console.WriteLine("x: {0} Ans: {1} Status: {2}", x, ans, exception);
//Console.WriteLine("Pref:{0} Next: {1} Stepval: {2} Formul:{3} x:{4} Ans:{5} Status:{}", pref, next, stepval, formul, x, ans, exception);
}
public static void NoAnsyet()
{
exception = "\nNo Solution yet...";
//Console.WriteLine(exception);
}
public static void Error()
{
exception = "\nNo Solution error!!";
Console.WriteLine(exception);
}
}
}
Because you set exception = "\ncomplete"; at different places. The \n at the beginning is a new line character.
Remove the \n
exception = "complete";
Same problem with other texts like "\nSolution Found!".
Using string interpolation makes string formatting more readable:
Replace
Console.WriteLine("Pref:{0} Next:{1} Step:{2} Formul:{3} x:{4} Ans:{5} Status:{6}",
pref, next, stepval, formul, x, ans, exception);
by
Console.WriteLine(
$"Pref:{pref} Next:{next} Step:{stepval} Formul:{formul} x:{x} Ans:{ans} Status:{exception}");
WriteLine writes in a New Line. You should try
Console.Write()
If you want to print right after your previous print.
The value to your variable exception is the reason why the console is printing on a different basically if you put a special character \n means new line hence all the methods you are calling have this special character.
Solution remove special characters and use the Console.WriteLine or Console.Write methods
As per the code provided you have not called the method i made some changes to the code
Edited code
and try to run the code status :No solution found yet
Thanks

C# XmlSerializer Problems with serializer.Serialize

Long story short, I am making an ATM application for a school assignment. Bank account information needs to be stored into a file to keep those account balances up to date.
I have two questions - (1) In the serialization process I get an error on line 49 that says:
(field)Account[] RunAccount.acctArray
An object reference is required for the non-static field, method, or property 'RunAccount.acctArray'
(2) Do my read-in and read-out serialization locations make sense?
I am very new at this and feel like I have no idea what I am doing so all advice is appreciated and welcome. Thanks!
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Bank_Midterm_Project
{
public class RunAccount
{
Account[] acctArray = new Account[3];
private static int i;
bool acctscreated = false;
bool acctsloaded = false;
private object test;
public static void Main(String[] args)
{
RunAccount ra = new RunAccount();
int input;
do
{
Console.WriteLine("Please enter a choice:");
Console.WriteLine("1) Populate Accounts");
Console.WriteLine("2) Load Accounts From File");
Console.WriteLine("3) Select Account");
Console.WriteLine("4) Exit");
input = Convert.ToInt32(Console.ReadLine());
if (input == 1 && ra.acctscreated == false)
{
ra.populateArray();
}
else if (input == 2 && ra.acctsloaded == false)
{
ra.readArray();
}
else if (input == 3 && ra.acctscreated == true)
{
ra.pickAccountMenu();
}
else if (input == 4)
{
Stream FileStream = File.Create("test.xml");
XmlSerializer serializer = new XMLSerializer(typeof(Account[]));
serializer.Serialize(FileStream, acctArray);
FileStream.Close();
}
else
{
if (input == 1 && ra.acctscreated == true)
{
Console.WriteLine("You have already populated the accounts. Please try again.");
}
else if (input == 2 && ra.acctscreated == true)
{
Console.WriteLine("You have already loaded the accounts. Please try again.");
}
else if (input == 3 && ra.acctscreated == false)
{
Console.WriteLine("You must create the accounts first. Please try again.");
}
}
} while (input != 5);
//ATM atm = new ATM();
//atm.topMenu();
//ra.writeArray();
//{
//}
}
//private void readArray()
//{
// throw new NotImplementedException();
public void readArray()
{
Stream FileStream = File.OpenRead("test.xml");
XmlSerializer deserializer = new XmlSerializer(typeof(Account[]));
acctArray = (Account[])deserializer.Deserialize(FileStream);
FileStream.Close();
}
//}
public void populateArray()
{
//int[] acctArray = new int[3];
//prompt for username
Console.WriteLine("Please enter three account numbers, separated by spaces:");
string[] tokens = Console.ReadLine().Split();
for (int i = 0; i < acctArray.Length; i++)
{
acctArray[i] = new Account(tokens[i]);
}
acctscreated = true;
}
public void pickAccountMenu()
{
string sinput = null;
int input = -1;
while (input != 4)
{
Console.WriteLine("Please enter 0, 1, or 2 for your account. 4 to quit.");
sinput = Console.ReadLine();
input = Convert.ToInt32(sinput);
if (input != -99)
{
acctArray[input].menu();
}
}
}
}
internal class XMLSerializer : XmlSerializer
{
public XMLSerializer(Type type) : base(type)
{
}
}
}
Use ra.acctArray. You have to access that property using the class instance variable.

Use a while loop to read in the entire text file and output a message a list with only the even numbers from the file to the screen

I can't figure out how to output a message a list with only the even numbers from the file to the screen.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EvenNumbersFile
{
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("NumbersFile.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadLine();
}
}
}
I think I understand what you want now. You need to parse the number in the file then check to see if it is evenly divisible by two. Here is some code to try:
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
{
int temp;
if (int.TryParse(line, out temp) && (temp % 2 == 0))
{
Console.WriteLine(line);
}
}
}
Something like this sounds like what you need:
while (line != null)
{
line = myReader.ReadLine();
int number = -1;
if (line != null)
{
if (Int32.TryParse(line, out number))
{
if (number % 2 == 0)
{
Console.WriteLine(number);
}
}
}
}
The .TryParse can be omitted if you can guarantee that the input file will only contain numbers.
More complete version:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrintEvenNumbers
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
SafeForWork();
Console.WriteLine();
JustShowingOff();
Console.ReadLine();
}
private static void SafeForWork()
{
StreamReader myReader = new StreamReader(#"C:\Users\Public\NumbersFile.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
int number = -1;
if (Int32.TryParse(line, out number))
{
if (number % 2 == 0)
{
Console.WriteLine(number);
}
}
}
myReader.Close();
}
private static void JustShowingOff()
{
List<String> Contents = File.ReadAllLines(#"C:\Users\Public\NumbersFile.txt").ToList();
List<String> Evens = Contents.Where(var => (Int32.Parse(var)) % 2 == 0).ToList();
Evens.ForEach(var => Console.WriteLine(var));
}
}
}
File contents:
1
2
4
13
6
99
8

Categories