Trying to get a valid integer from keyboard input - c#-4.0

I am trying to get a valid integer from the user input, the function I wrote must display an error message for these inputs..
1) 0 or a negative number
2) a string
It works for strings but not for 0 or negative numbers
I am unable to find my mistakes.. :-(
public int getValidNumber()
{
int temp_int;
while ((!int.TryParse(Console.ReadLine(), out temp_int)) && (temp_int > 0))
{
Console.WriteLine("Not a valid number....try again");
}
return temp_int;
}
Is it the correct way to use temp_int variable immediately....?

The most obvious mistake is that your while runs if the int is greater than 0, which you don't want:
//Assign to temp_int first:
int.TryParse(Console.ReadLine(), out temp_int);
while (temp_int < 1)
{
Console.WriteLine("Not a valid number....try again");
int.TryParse(Console.ReadLine(), out temp_int);
}

getValidNumber(Console.ReadLine());
...
public int getValidNumber(string input)
{
int temp_int = int.TryParse(input, out temp_int);
if (temp_int =< 0)
{
Console.WriteLine("Not a valid number....try again");
}
return temp_int;
}

Related

MQL4 Drawing a Dynamic Rectangle_Label with a Text in It

I am trying to draw a Rectangle Label with a text in it every tick.. I want a text to fit exactly in to a Rectangle_Label.. As a text i am using Label.. But cant get it to work exactly.. It is not correctly situated..
In Fact i would like to create a class that would do it all in one... Just like a rectangle with text in it that would be always having same co ordinance and size etc..
Any help would be greatly appreciated...
bool createRectangleLabel(long chart_ID,string name,string labelName,int shift,double price,string text,double xSize,double ySize,double xOffSet,double yOffSet,double xDistance,double yDistance)
{
if(ObjectCreate(chart_ID,labelName,OBJ_RECTANGLE_LABEL,0,TimeCurrent()-shift,price))
{
Print(xDistance+" "+yDistance);
ObjectSetInteger(chart_ID,labelName,OBJPROP_BGCOLOR,clrBlack);
ObjectSetInteger(chart_ID,labelName,OBJPROP_XDISTANCE,xDistance);
ObjectSetInteger(chart_ID,labelName,OBJPROP_YDISTANCE,yDistance);
ObjectSetInteger(chart_ID,labelName,OBJPROP_YSIZE,ySize);
ObjectSetInteger(chart_ID,labelName,OBJPROP_XSIZE,xSize);
ObjectSetString(chart_ID,labelName,OBJPROP_TEXT,text);
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,ANCHOR_CENTER);
return true;
}
else
{
Print("createRectangleLabel return error code: ",GetLastError());
Print("+--------------------------------------------------------------+");
return false;
}
}
bool createLineText(long chart_ID,string name,string labelName,int shift,double price,string text)
{
int xDistance=0;
int yDistance=0;
int xSize,xOffSet;
int ySize,yOffSet;
bool i=ChartTimePriceToXY(chart_ID,0,TimeCurrent(),price,xDistance,yDistance);
if(ObjectCreate(chart_ID,name,OBJ_LABEL,0,TimeCurrent()-shift,price))
{
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,clrWhite);
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,xDistance);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,yDistance);
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,ANCHOR_CENTER);
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clrWhite);
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,10);
xSize = ObjectGet(name,OBJPROP_XSIZE);
ySize = ObjectGet(name,OBJPROP_YSIZE);
xOffSet = ObjectGet(name,OBJPROP_XOFFSET);
yOffSet = ObjectGet(name,OBJPROP_YOFFSET);
TextGetSize(name,xSize,ySize);
createRectangleLabel(chart_ID,name,labelName,shift,price,text,xSize,ySize,xOffSet,yOffSet,xDistance,yDistance);
return true;
}
else
{
Print("createLineText return error code: ",GetLastError());
Print("+--------------------------------------------------------------+");
return false;
}
}
You cannot call ObjectCreate() every tick - it would return an error 4200.
If you check the object exists before creating, that would help. Alternative approach would be to try to create the object and assign it with some necessary properties (e.g., color of the object, anchor etc) in one block, and move it in another.
if(ObjectFind(chart_id,labelName)<0){
if(ObjectCreate(chart_ID,labelName,OBJ_RECTANGLE_LABEL,0,TimeCurrent()-shift,price)){
ObjectSetInteger(chart_ID,labelName,OBJPROP_BGCOLOR,clrBlack);//etc.
}
ObjectSetInteger(chart_ID,labelName,OBJPROP_XDISTANCE,xDistance);
ObjectSetInteger(chart_ID,labelName,OBJPROP_YDISTANCE,yDistance);//if you need to move the object or take other steps each tick, e.g. update text - do it here
}
You're thinking along the right lines when you say that you'd like to create a class. Fortunately for you, the standard library already includes all the classes you need to make chart objects. Documentation
Example Indicator:
#property strict
#property indicator_chart_window
#include <ChartObjects\ChartObjectsTxtControls.mqh>
class MyRectLabel : public CChartObjectRectLabel
{
CChartObjectLabel m_label;
public:
bool Create(long chart, const string name, const int window,
const int X, const int Y, const int sizeX, const int sizeY)
{
if(!CChartObjectRectLabel::Create(chart,name,window,X,Y,sizeX,sizeY))
return false;
return m_label.Create(chart, name + "_", window, X + 8, Y + 12);
}
bool Color(const color clr){
return m_label.Color(clr);
}
bool Description(const string text){
return m_label.Description(text);
}
bool FontSize(const int size){
return m_label.FontSize(size);
}
bool ToolTip(const string text){
return (this.ToolTip(text) && m_label.Tooltip(text));
}
};
//+------------------------------------------------------------------+
MyRectLabel rect_label;
//+------------------------------------------------------------------+
int OnInit()
{
if(!rect_label.Create(0, "rlabel", 0, 5, 25, 100, 50)
|| !rect_label.BackColor(clrWhiteSmoke)
|| !rect_label.Description("LABEL!")
|| !rect_label.Tooltip("I am a rectangle label")
|| !rect_label.Color(clrBlack)
|| !rect_label.FontSize(18)
)
return INIT_FAILED;
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
int start()
{
static double last_price = 0.;
rect_label.Description(DoubleToString(Bid, _Digits));
if(Bid > last_price)
rect_label.Color(clrLimeGreen);
else
rect_label.Color(clrRed);
last_price = Bid;
return 0;
}

How to call multi argument function using ArrayList?

Im trying to call this method from SDK
public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {
if (top < 0) {
throw new IllegalArgumentException("Top must be greater or equal to zero.");
}
if (left < 0) {
throw new IllegalArgumentException("Left must be greater or equal to zero.");
}
if (bottom < 1 || bottom <= top) {
throw new IllegalArgumentException("Bottom must be greater than zero and top.");
}
if (right < 1 || right <= left) {
throw new IllegalArgumentException("Right must be greater than zero and left.");
}
hasCrop = true;
cropTop = top;
cropLeft = left;
cropBottom = bottom;
cropRight = right;
return this;
}
How I can call the method if the parameters are from an Array or Map like this? Is that possible?
ArrayList arrayList = [299, 296, 301, 297]
crop(arraylist)
Java:
No you cant.
you will get this error:
Compilation Errors Detected
...
method crop in class Test cannot be applied to given types;
required: int,int,int,int
found: java.util.ArrayList<java.lang.Integer>
reason: actual and formal argument lists differ in length
Groovy:
Yes you can.
Check the sample code on groovyConsole.
def hello(int a, int b){
println "$a and $b"
}
hello(1, 2)
def param = [1,2]
hello(param)
public ThumborUrlBuilder crop(ArrayList params) {
if (params.size() != 4 ){
throw new IllegalArgumentException(...);
}
int top = params.get(0);
int left = params.get(1);
int bottom = params.get(2);
int right = params.get(3);
...
}
This is not directly possible in Java, because the function crop requires 4 parameters.
Passing the given ArrayList into the crop function would result in an error.
You could write your own function to handle the ArrayList for you like this:
public ThumboUrlBuilder special_crop(ArrayList arraylist){
crop(arraylist.get(0),arraylist.get(1),arraylist.get(2),arraylist.get(3));
}

what's different between StrCmpW and wcscmp?

Actually i changed code to next.
struct myclass {
bool operator() (std::wstring p1, std::wstring p2) {
int result = 0;
//// If character is alphabet, sorting need converse.
wint_t a1 = p1.at(0);
wint_t b2 = p2.at(0);
int r1 = iswalpha(a1);
int r2 = iswalpha(b2);
**// return code of iswalpha.
// 257 is Upper Alphabet,
// 258 is Lower Alphabet**
if ((r1 == 257 && r1 == 258) ||
(r2 == 258 && r2 == 257)) {
result = p2.compare(p1);
}
else {
result = p1.compare(p2);
}
if (result != 0) {
if (result == -1) {
return true;
}
else {
return false;
}
}
return false;
}
} wStrCompare;
void main() {
std::vector<std::wstring> wlist;
wlist.emplace_back(L"가나");
wlist.emplace_back(L"123");
wlist.emplace_back(L"abc");
wlist.emplace_back(L"타파");
wlist.emplace_back(L"하하");
wlist.emplace_back(L"!##$");
wlist.emplace_back(L"一二三");
wlist.emplace_back(L"好好");
wlist.emplace_back(L"QWERID");
wlist.emplace_back(L"ⓐⓑ");
wlist.emplace_back(L"☆★");
wlist.emplace_back(L"とばす");
std::sort(wlist.begin(), wlist.end(), wStrCompare);
}
Test Result
L"!##$"
L"123"
L"abc"
L"QWERID"
L"ⓐⓑ"
L"☆★"
L"とばす"
L"一二三"
L"好好"
L"가나"
L"타파"
L"하하"
is this good?
Please give me a some opinion.
Thanks!!
I change my code, but i still want to know "is there difference between StrCmpW and wcscmp" Please talk to me. thanks!
Old question
I use qsort with std::wstring(for unicode string), and use StrCmpW.
Previously, I used StrCmpLogicalW() with CString, CStringArray.
(These are depend on windows)
But my code run in linux too, not only in windows.
(CString is ATL(afx), StrCmpLogicalW() is in Shlwapi.h)
So I use std::wstring and wcscmp, but result is different.
Is there a difference between StrCmpW() and wcscmp()?
The Following is my code.(exactly not mine lol)
int wCmpName(const void* p1, const void *p2)
{
std::wstring* wszName1 = ((std::wstring *)(p1));
std::wstring* wszName2 = ((std::wstring *)(p2));
int wret = StrCmpW(wszName1->c_str(), wszName2->c_str());
// int wret = wcscmp(wszName1->c_str(), wszName2->c_str());
// When i use wcscmp, different result comes out.
return wret;
}
void wSort(std::vector<std::wstring> &arr)
{
qsort(arr.data(), arr.size(), sizeof(std::wstring), wCmpName);
}
Thanks!
Test Code
void main() {
std::vector<std::wstring> wlist;
wlist.emplace_back(L"가나");
wlist.emplace_back(L"123");
wlist.emplace_back(L"abc");
wlist.emplace_back(L"타파");
wlist.emplace_back(L"하하");
wlist.emplace_back(L"!##$");
wlist.emplace_back(L"一二三");
wlist.emplace_back(L"好好");
wlist.emplace_back(L"QWERID");
wlist.emplace_back(L"ⓐⓑ");
wlist.emplace_back(L"☆★");
wlist.emplace_back(L"とばす");
wSort(wlist);
}
Test Result
wcscmp
L"!##$"
L"123"
L"QWERID"
L"abc"
L"ⓐⓑ"
L"☆★"
L"とばす"
L"一二三"
L"好好"
L"가나"
L"타파"
L"하하"
StrCmpW
L"!##$"
L"☆★"
L"123"
L"ⓐⓑ"
L"abc"
L"QWERID"
L"とばす"
L"가나"
L"一二三"
L"타파"
L"하하"
L"好好"
p.s : WHY limit reputation?! limited Images, limited URLs.
Only text takes so long time.

How to get the integer value in TextBox?

I have one Text Box in windows application. This Text Box only allowed the integer value not string. Can anybody have solution ?
Convert it.
public int GetIntValue(TextBox tb)
{
try
{
return Convert.toInt32(tb.Text);
}
catch (Exception ex)
{
//This is called if the converting failed for some reason
}
return 0; //This should only return 0 if the textbox does not contain a valid integer value
}
Use it like this:
int number = GetIntValue(textBox1);
Hope this helps!
Use this.
int value = Convert.ToInt32(textBox1.Text);
You use this code and get your integer value.Thanks
I found a solution from C# How do I make a textbox that only accepts numbers
Hope it will help you.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}

searching in List<>

i want to find value in List<> but i am not getting the integer value. Here is my code from that i want to find the value in the List
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
try
{
//decimal find = decimal.Parse(txtnapsaserach.Text);
if (decimal.Parse(txtnapsaserach.Text) > 0)
{
List<NapsaTable> _napsatabs = this.napsaTableBindingSource.List as List<NapsaTable>;
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate.Equals(txtnapsaserach.Text)).ToList();
}
}
catch (Exception Ex)
{
}
}
any solution for me . Because this works for me when i try to find string value.
private void txtnapsaserach_TextChanged(object sender, EventArgs e)
{
float value;
if (!float.TryParse(txtnapsaserach.Text, out value))
return; // return if text cannot be parsed as float number
if (value > 0)
{
var napsatabs = napsaTableBindingSource.List as List<NapsaTable>;
napsaTableBindingSource.DataSource =
napsatabs.Where(p =>p.NapsaRate == value).ToList();
}
}
try this
i want to find value in List<> but i am not getting the integer value.
Your p.NapsaRate is either integer type or floating point number, (probably decimal) Convert your txtnapsaserach.Text to decimal value and then compare it in where clause.
decimal rate = 0;
if(!decimal.TryParse(txtnapsaserach.Text), out rate)
{
//Invalid number in textbox
}
this.napsaTableBindingSource.DataSource =
_napsatabs.Where(p =>p.NapsaRate == rate)).ToList();
if p.NapsaRate is of type double or float you can parse them accordingly using Double.TryParse or Double.Parse etc
The reason you are not getting any error is that you are using object.Equals method for comparing decimal value with string. You should always use == for equality comparison of value types.

Resources