I need help writing a program that takes in student info for three separate fields (ID Number, first name, last name). Then, sorts the table alphabetically based on the last name field. The user will input the student data, then I would like it to separate the last name data into two buckets which will then be put into a bubble sort. I am having trouble with adding the data into separate buckets.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _123_Assignment2
{
using System;
using static System.Console;
class Program
{
struct student
{
public int studentId;
public string firstName;
public string lastName;
};
static void Main(string[] args)
{
student[] studentInfo = new student[20];
string[] bucketLow = new string[0];
string[] bucketHigh = new string [0];
int x = 0;
int y = 0;
WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(ReadLine());
while (studentInfo[x].studentId != 999)
{
WriteLine("Enter first name:");
studentInfo[x].firstName = ReadLine();
WriteLine("Enter last name:");
studentInfo[x].lastName = ReadLine();
x++;
WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(ReadLine());
}
for (int j = 0; j < studentInfo.Length; j++)
{
if (studentInfo[j].lastName.CompareTo(studentInfo[j + 1].lastName) > 0)
bucketLow[y] = studentInfo[j].lastName;
else
bucketHigh[y] = studentInfo[j].lastName;
y++;
}
}
}
}
Try this code, you can check my comments for explanation:
student[] studentInfo = new student[20];
//Make sure you initialize the correct number of variables on your string
string[] bucketLow = new string[20];
string[] bucketHigh = new string[20];
int x = 0;
int y = 0;
//I commented out this line since you are already asking for inputs on without going on your counter scenario
//Console.WriteLine("Enter student ID number:");
//studentInfo[x].studentId = Convert.ToInt32(Console.ReadLine());
//I made changes on this line, since, you are doing a condition based on the number of increment on your counter
while (x <= 2)
{
//I put the enter student ID above since it will not be counted if it was put after the counter x
Console.WriteLine("Enter student ID number:");
studentInfo[x].studentId = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter first name:");
studentInfo[x].firstName = Console.ReadLine();
Console.WriteLine("Enter last name:");
studentInfo[x].lastName = Console.ReadLine();
x++;
}
for (int j = 0; j < x; j++)
{
//Make sure you put group all your conditions on round brackets to achieve your desired condition
if ((studentInfo[j].lastName.CompareTo(studentInfo[j + 1].lastName)) > 0)
bucketLow[y] = studentInfo[j].lastName;
else
bucketHigh[y] = studentInfo[j].lastName;
y++;
}
Related
Im completely new to coding and I've been given a challenge to create a histogram by asking a user to input a certain amount of numbers line by line. Which I have executed a for loop to handle with no issues. The difficulty I'm having is I'm trying to use a string which I've called (x) and contains (""). The challenge is to make the () symbol duplicate to the amount of the value entered by the user... Just wondering how I could code it in such a way so that it compares the user input value number to print the (*) the same amount equal to the number being entered!
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
string x = ("*");
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
for (int count= 0; count < userVal.Length; count ++)
{
}
A simple way might be to iterate through the responses, and use the string(char,cnt) constructor https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx.
It fills the string with a specific char, and specific length.
e.g.
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int numberToCollect = 10;
int[] answers = new int[numberToCollect];
int numberCollected = 0;
while(numberCollected<numberToCollect)
{
int parsedInt = 0;
if (int.TryParse(intConsole.ReadLine(),out parsedInt))
{
answers[numberCollected++] = parsedInt;
}
else
{
Console.WriteLine("Invalid number, try again!");
}
}
for(var cnt in answers)
{
Console.WriteLine(new String('*',cnt));
}
}
}
}
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] userVal = new int[8];
for (int count = 0; count < userVal.Length; count++)
{
if (userVal[count] <= 10)
{
Console.WriteLine("Please enter Number");
userVal[count] = int.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("ERROR, Number too BIG!");
}
}
foreach (var cnt in userVal)
{
Console.WriteLine(new String('*', cnt));
}
Console.ReadKey();
}
}
}
Create:
This class defines an Employee.
Member variables: ID (int), name (string), salary (double)
Member Methods: Constructors, input/output methods that perform I/O for an employee
Create:
This class defines an array of Employees
Member variables: An array of Employee, SIZE (int), currentSize (int)
Member Methods: Constructors, input/output methods, search/insert/delete/update methods.
Not sure exactly how to store 3 Employee variables inside a single array index.
Updated:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication16
{
class Employee
{
protected int id;
protected string name;
protected double salary;
public Employee()
{
}
public Employee(int _id, string nm, double sal)
{
id = _id;
name = nm;
salary = sal;
}
public void PrintEmployee()
{
Console.WriteLine("id: {0}", id);
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Salary: {0}", salary);
}
}
class EmployeeArray : Employee
{
private Employee[] a;
private int currSize;
private const int SIZE = 100;
public EmployeeArray()
: base()
{
}
public EmployeeArray(int s, int _id, string nm, double sal)
: base(_id, nm, sal)
{
a = new Employee[SIZE];
if (s > SIZE)
Console.WriteLine("Array size is overflow!");
else if (s == SIZE)
Console.WriteLine("Array is full.");
else
currSize = s;
}
public void Input()
{
a = new Employee[3];
for (int i = 0; i < currSize; i++)
{
a[i] = new Employee(id, name, salary);
}
}
public void Output()
{
Console.WriteLine("Array is: ");
foreach (Employee x in a)
Console.WriteLine("a[{0}]= {1}", name, x);
}
public int Search(int key)
{
for (int i = 0; i < currSize; i++)
{
//if (a[i] == key)
// return i;
}
return -1;
}
public void Insert()
{
if (currSize == SIZE)
{
Console.Write("Array is full! ");
return;
}
Console.WriteLine("Enter a number to insert: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter the index to where it is to insert: ");
int pos = int.Parse(Console.ReadLine());
for (int i = currSize; i > pos; i--)
a[i] = a[i - 1];
//a[pos] = y;
currSize++;
}
public void Delete()
{
if (currSize == 0)
{
Console.WriteLine("Array is empty! ");
return;
}
Console.Write("Delete by value (1) or by index (2): ");
int key = int.Parse(Console.ReadLine());
int pos = -1;
if (key == 1)
{
Console.WriteLine("Enter the number to delete: ");
int d = int.Parse(Console.ReadLine());
pos = Search(d);
while (pos == -1)
{
Console.WriteLine("The number does not exist, enter again: ");
d = int.Parse(Console.ReadLine());
pos = Search(d);
}
}
else if (key == 2)
{
Console.WriteLine("Enter the index to delete from: ");
pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos > currSize)
{
Console.WriteLine("The index is out of range, enter again: ");
pos = int.Parse(Console.ReadLine());
}
}
else
return;
for (int i = pos; i < currSize; i++)
a[i] = a[i + 1];
currSize--;
if (currSize <= 0)
Console.Write("Array is empty! ");
}
public void Update()
{
Console.WriteLine("Enter the index where to update: ");
int pos = int.Parse(Console.ReadLine());
while (pos < 0 || pos >= currSize)
{
Console.WriteLine("The index you entered is not valid, enter again: ");
pos = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter the new value: ");
int x = int.Parse(Console.ReadLine());
//a[pos] = x;
Console.Write("Update complete! ");
}
}
class Program
{
//static char ShowMenu()
//{
// Console.WriteLine("\nEnter the letter of operation: \n(o)Print, (s)Search, (i)Insertion, (d)Deletion, (u)Update, (e)Exit\n");
// return char.Parse(Console.ReadLine());
//}
static void Main(string[] args)
{
//char sel = ' ';
Console.Write("Enter number of Employees; ");
int i = 0;
int s = int.Parse(Console.ReadLine());
while ( i < s )
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Enter id: ");
int _id = int.Parse(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("Enter Name: ");
string nm = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Enter Salary: ");
double sal = int.Parse(Console.ReadLine());
EmployeeArray arr = new EmployeeArray(s, _id, nm, sal);
i++;
}
}
}
}
This reads like homework but I'll help you out.
You create your employee class with it's three members and methods.
then you create an array of employee objects.
//How Many employee objects do you need. Let's assume 10 for example
int NUM = 10;
Employee[] employees = new Employee[NUM]; // Declare an An array of employee's of length 10 (zero indexed from 0 - 9)
//Assuming you have made Getters and Setters
//Then if you need to access an employee object's member(s)
employees[0].getId(); //get the first employee's id
employees[0].getName(); //get the first employee's name
employees[0].getSalary(); //get the first employee's name
// Or set them like
employees[4].setId(12); //set the fifth employee's id to 12
employees[4].setName("Joe Bloggs"); //set the fifth employee's name to Joe Bloggs
employees[4].setSalary("30000"); //set the fifth employee's salary to 30000
MSDN C# Arrays
MSDN Classes
There are lots of problems with the code you posted. I'm just going to highlight a few issues, especially since this implementing arrays sounds a lot like computer science homework.
EmployeeArray inherits from Employee. Think about the meaning of public and private keywords and base classes.
Your functions all do more than one thing. This really complicates your code, and is going to result in bugs. Focus on straightforward code that does one thing and communicates what it does.
Users could crash your program in several places by entering something other than a number.
Lastly, to directly answer your question, you can access arrays through an index. You can't store three separate Employee objects in the same index. You've accessed array objects in other parts of your code, so it seems like you understand that you can store different values in different indexes.
My code asks the user to enter a certain amount of students and to enter there name and score depends on how many students there are. My question is, how would I use an if statement to find out the student with the highest score. (C#)
class Class1
{
public void studentCount()
{
int studentcount;
int i;
int x;
string studentname = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
}
}
Keep track of the current highest x (student's score) and if a new one that's entered is higher than the last highest, update the last highest score's variable and that student's name. You'll need to use one more variable for this to keep track of the current max score. You can always update the student's name to match the student with the max score. After the loop, you can output that student's score and name.
Respecting your actual code, probably this would suit you well.
int studentcount = 0, i = 0, x = 0, highestScore = 0;
string studentname = "", highestScoreStudentName = "";
Console.WriteLine("Enter how many students there are: ");
studentcount = Convert.ToInt32(Console.ReadLine());
{
for (i = 1; i <= studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
if (x > highestScore)
{
highestScore = x;
highestScoreStudentName = studentname;
}
}
}
There are many ways to accomplish this. Below are a few ways. Best would be the take advantage of OOP and create classes for what you need to do, but of course there are other ways to do what you want.
Sticking with your current method:
public void studentCount()
{
string highestScoringStudent;
int highestScore = 0;
Console.WriteLine("Enter how many students there are: ");
var studentCount = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < studentCount; i++)
{
Console.WriteLine("Enter students name: ");
var tempStudent = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
var tempScore = Convert.ToInt32(Console.ReadLine());
if(tempScore > highestScore)
{
highestScore = tempScore;
highestScoringStudent = tempStudent;
}
}
}
With a dictionary to keep track of your students:
public void StudentCount()
{
var students = new Dictionary<string, int>();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var name = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
var score = Convert.ToInt32(Console.ReadLine());
students.Add(name, score);
}
var highestStudent = students.OrderByDescending(x => x.Value).FirstOrDefault()
Console.WriteLine("{0} scored {1}", highestStudent.Key, highestStudent.Value);
}
Using OOP:
public class TestEntry
{
public string StudentName { get; set; }
public int Score { get; set; }
}
public class SomeClass
{
readonly List<TestEntry> _testEntries = new List<TestEntry>();
public void EnterTests()
{
_testEntries.Clear();
var count = Convert.ToInt32(Console.ReadLine());
for (var i = 0; i < count; i++)
{
Console.WriteLine("Enter Student's Name:");
var testEntry = new TestEntry();
testEntry.StudentName = Console.ReadLine();
Console.WriteLine("Enter Student's Score:");
testEntry.Score = Convert.ToInt32(Console.ReadLine());
_testEntries.Add(testEntry);
}
}
public void PrintHighestScoringStudent()
{
var highestTest = _testEntries.OrderByDescending(x => x.Score).FirstOrDefault();
if (highestTest == null)
{
Console.WriteLine("No tests entered.");
return;
}
Console.WriteLine("{0} scored {1}", highestTest.StudentName, highestTest.Score);
}
}
use array [] and sort it then top most value is higher
Everton's solution will work, but I would think that you might be interested in keeping track of all scores. In that case, you could use an Array as suggested, but a better solution is probably to use a SortedList.
SortedList<int> students = new SortedList<int>();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(x);
}
int max = students.Last; //Default sorting is low to high,
//though this could be changed if
//you want to look into it.
If you wanted to keep track of scores with respect to the student, you could use a List<Tuple<string, int>>, but without some finagling it would not be possible to sort it. However, using Linq finding the max value is not difficult.
List<Tuple<string, int> >students = new List<Tuple<string, int> >();
...
for (int i = 0; i < studentcount; i++)
{
Console.WriteLine("Enter students name: ");
studentname = Convert.ToString(Console.ReadLine());
Console.WriteLine("Enter students score: ");
x = Convert.ToInt32(Console.ReadLine());
students.Add(studentname, x);
}
int max = students.Max(a => a.Item2).FirstorDefault();
I am trying to ask the user to input 10 numbers. After receiving the numbers, I am storing them in an array followed by printing the array. I came up with the following code to do the task but it is not printing the array.
Also feel that I may have rattled on way too much code for a simple task. Do note that I am very new to c# thus not familiar with advanced stuff or possibly even most of basic stuff. Even the "convert.toInt32", I adopted from reading around and not taught in class yet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_Array
{
class Program
{
static void Main(string[] args)
{
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
a = Convert.ToInt32(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = Convert.ToInt32(Console.ReadLine());
d = Convert.ToInt32(Console.ReadLine());
e = Convert.ToInt32(Console.ReadLine());
f = Convert.ToInt32(Console.ReadLine());
g = Convert.ToInt32(Console.ReadLine());
h = Convert.ToInt32(Console.ReadLine());
i = Convert.ToInt32(Console.ReadLine());
j = Convert.ToInt32(Console.ReadLine());
int[] newArray = {a,b,c,d,e,f,g,h,i,j};
Console.WriteLine(newArray);
Console.ReadLine();
}
}
}
use a for loop.
int[] newArray = new int[10];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
You can use the same loop to display as well:
for (int i = 0; i < newArray.Length; i++)
{
Console.WriteLine(newArray[i]);
}
The ToString method of arrays (which is what Console.WriteLine is calling in your code) isn't overloaded to print out the contents of the array. It leaves the basic object implementation of just printing the type name.
You need to manually iterate the array and print out the individual values (or use a method that will do that for you).
I.e.
foreach(var item in array)
Console.WriteLine(item)
or
Console.WriteLine(string.Join("\n", array));
static void Main(string[] args)
{
int[] rollno = new int[10];
Console.WriteLine("Enter the 10 numbers");
for (int s = 0; s < 9; s++)
{
rollno[s] = Convert.ToInt32(Console.ReadLine());
rollno[s] += 110;
}
for (int j = 0; j < 9; j++)
{
Console.WriteLine("The sum of first 10 numbers is : {0}", rollno[j]);
}
Console.ReadLine();
}
}
}
You could simplify things a lot with the following:
static void Main(string[] args)
{
int newArray = new int[10];
Console.WriteLine("Please input 10 numbers. Press 'ENTER' after each number.");
for (int i = 0; i < 10; i++) {
newArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The values you've entered are:");
Console.WriteLine(String.Join(", ", newArray));
Console.ReadLine();
}
I'm currently writing a program that takes a persons name and 5 variables. Then with those 5 variables I'm tasked with finding the avg/sample variance. My current code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userName = "";
string variables = "";
int[] vars = parseVariableString(variables);
vars = new int[5];
int sum = 0;
Console.Write("Please enter your name: ", userName);
userName = Console.ReadLine();
Console.ReadLine();
Console.Write("Please enter 5 numbers with a space or coma inbetween: ", vars);
for (int i = 0; i < vars.Length; i++)
{
int number = vars[i];
sum += number;
}
float avg = sum/(float)vars.Length;
float variance = 0;
for (int i = 0; i < vars.Length; i++)
{
int number = vars[i];
float f = number - avg;
variance += (float)Math.Pow(f, 2);
}
float sv = variance / (vars.Length - 1);
Console.Write(" Your name is: ", userName);
Console.ReadLine();
Console.Write("The average of your numbers is: ", avg);
Console.ReadLine();
Console.Write("The sample variance of your numbers is: ", sv);
Console.ReadKey();
}
private static int[] parseVariableString(String variables)
{
String[] varArray = variables.Split(' ', ',');
int[] intArray = new int[varArray.Length];
for (int i = 0; i < varArray.Length; i++)
{
String variable = varArray[i];
int integer = Convert.ToInt32(variable);
intArray[i] = integer;
}
return intArray;
}
}
}
I'm getting the
Input string was not in correct format
error at int integer = Convert.ToInt32(variable);. I'm not understanding why exactly I'm getting this error. I looked online for what it means, a lot of people say to use an int.parse but from what I read you get this because the variable doesn't recognize that there is a value associated with it. Any help would be greatly appreciated.
string variables = "";
int[] vars = parseVariableString(variables);
You're declaring an empty string, and then trying to convert that string into an int.
private static int[] parseVariableString(String variables)
{
String[] varArray = variables.Split(' ', ',');
int[] intArray = new int[varArray.Length];
for (int i = 0; i < varArray.Length; i++)
{
String variable = varArray[i];
int integer = Convert.ToInt32(variable);
intArray[i] = integer;
}
return intArray;
}
As well as when you're passing in an empty string, there's nothing to split, and thus your array is empty.