Program is in c# The task is to create 3 different classes, for this example we\
ID: 3601061 • Letter: P
Question
Program is in c#
The task is to create 3 different classes, for this example we'll call it Items as base.
The task is to create only one array of size 10 Items.
We streamread in to get the 5 items names for potions and spells from 2 different text files ("potions.txt") ( spells.txt)
Potions.txt holds 5 names, and Spells.txt holds 5 names.
streamread should be random between the file potions and file spells if one is empty we use the other file to fill in the empty variables in Items.
quantity, damage, heals are all random numbers from 1-10
Items
string Name
int Quantity
Potions : Items
int Heal
Spells : Items
int Damage
Display:
Spell Magic Blast : QTY: 5 : Deals 4 damage
Potion Red Pot : Qty: 3 : Heals 6 Points
Spell Icy Domain : Qty 3: Deals 9 damage
Please provide code for the scenario above.
Explanation / Answer
using System;
using System.IO;
using System.Collections.Generic;
namespace ItemsMain {
class Items {
public string Name;
public int Quantity;
}
class Potions : Items{
public int Heal;
}
class Spells : Items{
public int Damage;
}
class ItemsMain {
static void Main(string[] args) {
try {
int count = 0;
int countPor = 0;
List<Potions> listPortion=new List<Potions>();
List<Spells> listSpells=new List<Spells>();
Random r = new Random();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:/Potions.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Potions p = new Potions();
p.Name = line;
p.Quantity = r.Next(1, 10);
p.Heal = r.Next(1, 10);
listPortion.Add(p);
if(++count>=5) break;
}
}
using (StreamReader sr = new StreamReader("c:/Spells.txt")) {
string line;
countPor = count;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Spells s = new Spells();
s.Name = line;
s.Quantity = r.Next(1, 10);
s.Damage = r.Next(1, 10);
listSpells.Add(s);
if(++count>=10) break;
}
for(int i=0; i<10; i++){
if(i<countPor){
Console.WriteLine("Portion" + listPortion[i].Name + " : QTY: " + listPortion[i].Quantity + " : Heals " + listPortion[i].Heal + " Points");
}
else{
Console.WriteLine("Spell" + listSpells[i-countPor].Name + " : QTY: " + listSpells[i-countPor].Quantity + " : Deals " + listSpells[i-countPor].Damage + " damage");
}
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
}
Here I have used two files "c:/Potions.txt" and "c:/Spells.txt". In these files the names should be line by line. In other word, each line should have one name.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.