I'm having trouble calling my methods. I have 2 separate files. When the user types S then the shake method in my other file will be invoked. So then when the user gets the answer it will be random.
I confused about how to bring that method in another file. Below are both files.
Program.cs:
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
public static string userAnswer = "";
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
}
else
{
//Call Method Shake()
}
}
else if (input == "A") {
userAnswer = Console.ReadLine();
}
else if (input == "G") {
//Call Method GetAnswer()
}
} while (input != "E");
}
Magic8Ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Magic8Ball_Logic
{
public class Magic8Ball
{
private List<string> _answers;
private int _currentIndex;
private string randomString;
public Magic8Ball()
{
_answers = new List<string>();
_answers.Add("It is certain.");
_answers.Add("It is decidedly so.");
_answers.Add("Without a doubt.");
}
public Magic8Ball(List<string> answers)
{
//I won't use the 20 default. use the ones passed in .
_answers = answers;
}
public void Shake()
{
//picking the index of the answer to show the user
Random r = new Random();
int index = r.Next(_answers.Count);
randomString = _answers[index];
}
public string GetAnswer()
{
//using the index picked by shake to return the answer
//return "";
return randomString;
}
public int AnswerCount
{
get { return _answers.Count; }
}
/* public override string ToString()
{
foreach (var el in _answers)
{
return el;
}
}*/
}
}
First of all you must create an object of this class,then invoke the method.
**Edit**
ball.Shake();
As it was written here: https://stackoverflow.com/a/55986849/10128127
Your Program.cs should be updated like:
replace this comment
//Call Method Shake() with
ball.Shake();
replace this comment
//Call Method GetAnswer() with
ball.GetAnswer();
Related
This question already has answers here:
static imports in c#
(5 answers)
Closed 1 year ago.
I tried to use something like using Printer; but it doesn't work.
I just want use P(); instead of Printer.P();
File Printer.cs
using System;
namespace animals
{
public class Printer
{
public static void P()
{
P("\a");
}
public static void P(object val, bool doEnterAfterLine = true, bool printInOneLine = false)
{
P(val.ToString());
if (doEnterAfterLine)
Console.WriteLine(); //enter
}
static void P(bool printSeparator = false)
{
if (printSeparator == false)
return;
P("---------------------------------------------------------", true);
}
static void P(string value = "none", bool modifyColor = false, bool ding = false, bool printInOneLine = false)
{
var oldColor = Console.ForegroundColor;
if (modifyColor)
Console.ForegroundColor = ConsoleColor.Magenta;
if (printInOneLine)
Console.Write(value + " ");
else
Console.WriteLine(value);
Console.ForegroundColor = oldColor; //recover color
if (ding)
{
Console.Write("\a");
}
}
}
}
File Program.cs
using System;
// this resolve problem: using static animals.Printer;
namespace animals
{
class Program
{
static void Main(string[] args)
{
Printer.P(); // it works
P(); // info: does not exist in current context
}
}
}
Use using static <namespace>.<class>; to access the members of <class> without qualifying its name.
using static animals.Printer;
Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}
You are making a recursive call at the end of GetNewDvdInfo(), just remove it.
You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.
I'm working on a hangman game that runs in the console and trying to check whether a guessed letter is part of a word that is stored in a char array. When I try to run this and input a letter that is true, no exceptions are raised; however, when I enter a letter that is not part of the word, I get a FormatException saying that the string must be only one character long. Keep in mind that I enter one character when I get this exception. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Game game = new Game();
if(game.CheckAnswer())
{
Console.WriteLine("true");
}
else if(!game.CheckAnswer())
{
Console.WriteLine("false");
}
}
}
class Word
{
public static string GetWord()
{
string[] words = new string[5]{"alpha", "bravo", "charlie", "delta", "echo"};
Random random = new Random();
return words[random.Next(5)];
}
public char[] correctAnswer = GetWord().ToCharArray();
}
class Game
{
static char guessLetter;
static List<char> correctGuesses = new List<char>();
static List<char> incorrectGuesses = new List<char>();
Word word = new Word();
public bool CheckAnswer()
{
guessLetter = Convert.ToChar(Console.ReadLine());
if (word.correctAnswer.Contains(guessLetter))
{
return true;
}
else if (!word.correctAnswer.Contains(guessLetter))
{
return false;
}
else
{
return false;
}
}
}
Yes, I've checked other answers, and no, they did not have the solution to my problem.
My bad didn't check your code thoroughly. When you call the method in if else cases it will run them. So you were checking the results twice.
if the letter you enter is a wrong one it will be checked in both if and else cases which calls it twice.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Game game = new Game();
//dont call the method in if else save the result in a var first maybe
Console.WriteLine(game.CheckAnswer());
}
}
class Word
{
public static string GetWord()
{
string[] words = new string[5]{"alpha", "bravo", "charlie", "delta", "echo"};
Random random = new Random();
return words[random.Next(5)];
}
public char[] correctAnswer = GetWord().ToCharArray();
}
class Game
{
static char guessLetter;
static List<char> correctGuesses = new List<char>();
static List<char> incorrectGuesses = new List<char>();
Word word = new Word();
public bool CheckAnswer()
{
guessLetter = Convert.ToChar(Console.ReadLine());
//you can return the result directly
return word.correctAnswer.Contains(guessLetter);
}
}
Your problem is likely in your Main function. If the input character isn't in the word you actually end up asking for input from the console a second time.
Try changing it to:
static void Main(string[] args)
{
Game game = new Game();
bool answer = game.CheckAnswer(); // now you are only asking for input once
if(answer) Console.WriteLine("true");
else Console.WriteLine("false");
}
and see what happens.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
while (true)
{
Game game = new Game();
if (game.CheckAnswer())
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
}
}
class Word
{
public static string GetWord()
{
string[] words = new string[5] { "alpha", "bravo", "charlie", "delta", "echo" };
Random random = new Random();
return words[random.Next(5)];
}
public char[] correctAnswer = GetWord().ToCharArray();
}
class Game
{
static char guessLetter;
static List<char> correctGuesses = new List<char>();
static List<char> incorrectGuesses = new List<char>();
Word word = new Word();
public bool CheckAnswer()
{
guessLetter = Console.ReadKey().KeyChar;
if (word.correctAnswer.Contains(guessLetter))
{
Console.WriteLine();
return true;
}
Console.WriteLine();
return false;
}
}
I am evaluating Winnovative's PdfToText library and have run into something that concerns me.
Everything runs fine and I am able to extract the text content from a small 20k or less pdf immediately if I am running a console application. However, if I call the same code from the NUnit gui running it takes 15-25 seconds (I've verified it's PdfToText by putting a breakpoint on the line that extracts the text and hitting F10 to see how long it takes to advance to the next line).
This concerns me because I'm not sure where to lay blame since I don't know the cause. Is there a problem with NUnit or PdfToText? All I want to do is extract the text from a pdf, but 20 seconds is completely unreasonable if I'm going to see this behavior under certain conditions. If it's just when running NUnit, that's acceptable, but otherwise I'll have to look elsewhere.
It's easier to demonstrate the problem using a complete VS Solution (2010), so here's the link to make it easier to setup and run (no need to download NUnit or PdfToText or even a sample pdf):
http://dl.dropbox.com/u/273037/PdfToTextProblem.zip (You may have to change the reference to PdfToText to use the x86 dll if you're running on a 32-bit machine).
Just hit F5 and the NUnit Gui runner will load.
I'm not tied to this library, if you have suggestions, I've tried iTextSharp (way too expensive for 2 lines of code), and looked at Aspose (I didn't try it, but the SaaS license is $11k). But they either lack the required functionality or are way too expensive.
(comment turned into answer)
How complex are your PDFs? The 4.1.6 version of iText allows for a closed sourced solution. Although 4.1.6 doesn't directly have a text extractor it isn't too terribly hard to write one using the PdfReader and GetPageContent().
Below is the code I used to extract the text from the PDF using iTextSharp v4.1.6. If it seems overly verbose, it's related to how I'm using it and the flexibility required.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
namespace ClassLibrary1
{
public class PdfToken
{
private PdfToken(int type, string value)
{
Type = type;
Value = value;
}
public static PdfToken Create(PRTokeniser tokenizer)
{
return new PdfToken(tokenizer.TokenType, tokenizer.StringValue);
}
public int Type { get; private set; }
public string Value { get; private set; }
public bool IsOperand
{
get
{
return Type == PRTokeniser.TK_OTHER;
}
}
}
public class PdfOperation
{
public PdfOperation(PdfToken operationToken, IEnumerable<PdfToken> arguments)
{
Name = operationToken.Value;
Arguments = arguments;
}
public string Name { get; private set; }
public IEnumerable<PdfToken> Arguments { get; private set; }
}
public interface IPdfParsingStrategy
{
void Execute(PdfOperation op);
}
public class PlainTextParsingStrategy : IPdfParsingStrategy
{
StringBuilder text = new StringBuilder();
public PlainTextParsingStrategy()
{
}
public String GetText()
{
return text.ToString();
}
#region IPdfParsingStrategy Members
public void Execute(PdfOperation op)
{
// see Adobe PDF specs for additional operations
switch (op.Name)
{
case "TJ":
PrintText(op);
break;
case "Tm":
SetMatrix(op);
break;
case "Tf":
SetFont(op);
break;
case "S":
PrintSection(op);
break;
case "G":
case "g":
case "rg":
SetColor(op);
break;
}
}
#endregion
bool newSection = false;
private void PrintSection(PdfOperation op)
{
text.AppendLine("------------------------------------------------------------");
newSection = true;
}
private void PrintNewline(PdfOperation op)
{
text.AppendLine();
}
private void PrintText(PdfOperation op)
{
if (newSection)
{
newSection = false;
StringBuilder header = new StringBuilder();
PrintText(op, header);
}
PrintText(op, text);
}
private static void PrintText(PdfOperation op, StringBuilder text)
{
foreach (PdfToken t in op.Arguments)
{
switch (t.Type)
{
case PRTokeniser.TK_STRING:
text.Append(t.Value);
break;
case PRTokeniser.TK_NUMBER:
text.Append(" ");
break;
}
}
}
String lastFont = String.Empty;
String lastFontSize = String.Empty;
private void SetFont(PdfOperation op)
{
var args = op.Arguments.ToList();
string font = args[0].Value;
string size = args[1].Value;
//if (font != lastFont || size != lastFontSize)
// text.AppendLine();
lastFont = font;
lastFontSize = size;
}
String lastX = String.Empty;
String lastY = String.Empty;
private void SetMatrix(PdfOperation op)
{
var args = op.Arguments.ToList();
string x = args[4].Value;
string y = args[5].Value;
if (lastY != y)
text.AppendLine();
else if (lastX != x)
text.Append(" ");
lastX = x;
lastY = y;
}
String lastColor = String.Empty;
private void SetColor(PdfOperation op)
{
lastColor = PrintCommand(op).Replace(" ", "_");
}
private static string PrintCommand(PdfOperation op)
{
StringBuilder text = new StringBuilder();
foreach (PdfToken t in op.Arguments)
text.AppendFormat("{0} ", t.Value);
text.Append(op.Name);
return text.ToString();
}
}
}
And here's how I call it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp.text.pdf;
namespace ClassLibrary1
{
public class PdfExtractor
{
public static string GetText(byte[] pdfBuffer)
{
PlainTextParsingStrategy strategy = new PlainTextParsingStrategy();
ParsePdf(pdfBuffer, strategy);
return strategy.GetText();
}
private static void ParsePdf(byte[] pdf, IPdfParsingStrategy strategy)
{
PdfReader reader = new PdfReader(pdf);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
byte[] page = reader.GetPageContent(i);
if (page != null)
{
PRTokeniser tokenizer = new PRTokeniser(page);
List<PdfToken> parameters = new List<PdfToken>();
while (tokenizer.NextToken())
{
var token = PdfToken.Create(tokenizer);
if (token.IsOperand)
{
strategy.Execute(new PdfOperation(token, parameters));
parameters.Clear();
}
else
{
parameters.Add(token);
}
}
}
}
}
}
}
The following code outputs:
http://www.google.com
http://www.google.com&lang
What is the simplest way to change the code so it outputs:
http://www.google.com
http://www.google.com&lang=en¶m2=this¶m3=that
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestRegex9928228
{
class Program
{
static void Main(string[] args)
{
string text1 = "try out [url=http://www.google.com]this site (http://www.google.com)[/url]";
Console.WriteLine(text1.ExtractParameterFromBbcodeUrlElement());
string text2 = "try out [url=http://www.google.com&lang=en¶m1=this¶m2=that]this site (http://www.google.com)[/url]";
Console.WriteLine(text2.ExtractParameterFromBbcodeUrlElement());
Console.ReadLine();
}
}
public static class StringHelpers
{
public static string ExtractParameterFromBbcodeUrlElement(this string line)
{
if (line == null)
return "";
else
{
if (line.Contains("]"))
{
List<string> parts = line.BreakIntoParts(']');
if (parts[0].Contains("="))
{
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return sides[1];
else
return "";
}
else
return "";
}
else
return "";
}
}
public static List<string> BreakIntoParts(this string line, char separator)
{
if (String.IsNullOrEmpty(line))
return new List<string>();
else
return line.Split(separator).Select(p => p.Trim()).ToList();
}
}
}
Simplest or most efficient? You're asking two different questions it seems. Simplest would be something like this:
Change:
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return sides[1];
To:
List<string> sides = parts[0].BreakIntoParts('=');
if (sides.Count > 1)
return parts[0].Replace(sides[0], "");
Edit: Looks like you changed title to remove "most efficient". Here's the simplest change (fewest lines of code changed) that I see.