Search Results

Search found 6374 results on 255 pages for 'double underscore'.

Page 108/255 | < Previous Page | 104 105 106 107 108 109 110 111 112 113 114 115  | Next Page >

  • loop is cut one element of the array

    - by Walaa
    The problem is : Write a program that reads a number n and then declares an array of n elements. The program then fills the array with the first n numbers, where each number is two to the power of the previous. Finally, display array’s contents. My code : import java.util.*; public class Q1 { static Scanner scan = new Scanner (System.in); public static void main(String args [] ) { int num; int i = 0; System.out.println("Enter a number :"); num = scan.nextInt(); double [] a=new double[num]; a[0]= num ; for ( ;i<=a.length-1 ; i++) { a[i+1] = Math.pow(2,a[i]); System.out.println((int)(a[i]) ); } } } The error is : ----jGRASP exec: java Q1 Enter a number : 4 4 16 65536 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Q1.main(Q1.java:16) ----jGRASP wedge2: exit code for process is 1. why it says that? And the number by user printed twice!

    Read the article

  • C# specifying generic delegate type param at runtime

    - by smerlin
    following setup, i have several generic functions, and i need to choose the type and the function identified by two strings at runtime. my first try looked like this: public static class FOOBAR { public delegate void MyDelegateType(int param); public static void foo<T>(int param){...} public static void bar<T>(int param){...} public static void someMethod(string methodstr, string typestr) { MyDelegateType mydel; Type mytype; switch(typestr) { case "int": mytype = typeof(int); break; case "double": mytype = typeof(double); break; default: throw new InvalidTypeException(typestr); } switch(methodstr) { case "foo": mydel = foo<mytype>; //error break; case "bar": mydel = bar<mytype>; //error break; default: throw new InvalidTypeException(methodstr); } for(int i=0; i<1000; ++i) mydel(i); } } since this didnt work, i nested those switchs (a methodstr switch inside the typestr switch or viceversa), but that solution is really ugly and unmaintainable. The number of types is pretty much fixed, but the number of functions like foo or bar will increase by high numbers, so i dont want nested switchs. So how can i make this working without using nested switchs ?

    Read the article

  • What characters are widely supported in CSS class names?

    - by last-child
    As detailed here among other places, the only valid characters in a html/css class name is a-z, A-Z, 0-9, hyphen and underscore, and the first character should be a letter. But in practice, what characters are in fact supported by most browsers? More specifically, I wonder what browsers properly understands a slash (/) in a class name, and what browsers support class names starting with a number. I'm primarily interested in getting an answer for html rather than xhtml, in case there is a difference. Thank you.

    Read the article

  • Python: Regex outputs 12_34 - I need 1234

    - by Guy F-W
    So I have input coming in like: 12_34 5_6_8_2 4___3 1234 and the output I need from it is: 1234, 5682, 43, 1234 I'm currently working with r'[0-9]+[0-9_]*'.replace('_','') which (as far as I can tell) successfully rejects any input which is not a combination of numeric digits and under-scores, where the underscore cannot be the first character. However, replacing the _ with the empty string causes 12_34 to come out as 12 and 34. Is there a better method than 'replace' for this? Or could I adapt my regex to deal with this problem?

    Read the article

  • Cannot make a static reference to the non-static type MyRunnable

    - by kaiwii ho
    Here is the whole code : import java.util.ArrayList; public class Test{ ThreadLocal<ArrayList<E>>arraylist=new ThreadLocal<ArrayList<E>>(){ @Override protected ArrayList<E> initialValue() { // TODO Auto-generated method stub //return super.initialValue(); ArrayList<E>arraylist=new ArrayList<E>(); for(int i=0;i<=20;i++) arraylist.add((E) new Integer(i)); return arraylist; } }; class MyRunnable implements Runnable{ private Test mytest; public MyRunnable(Test test){ mytest=test; // TODO Auto-generated constructor stub } @Override public void run() { System.out.println("before"+mytest.arraylist.toString()); ArrayList<E>myarraylist=(ArrayList<E>) mytest.arraylist.get(); myarraylist.add((E) new Double(Math.random())); mytest.arraylist.set(myarraylist); System.out.println("after"+mytest.arraylist.toString()); } // TODO Auto-generated method stub } public static void main(String[] args){ Test test=new Test<Double>(); System.out.println(test.arraylist.toString()); new Thread(new MyRunnable(test)).start(); new Thread(new MyRunnable(test)).start(); System.out.println(arraylist.toString()); } } my questions are: 1\ why the new Thread(new MyRunnable(test)).start(); cause the error: Cannot make a static reference to the non-static type MyRunnable ? 2\ what is the static reference refer to right here? thx in advanced

    Read the article

  • android populating gridivew from a url string

    - by user1685991
    I am building an android application in which i am trying to read data from a url and want to display the data in a gridview. But i have some problem or dont understand to how to display the array list on grdiview. Here is my code for reading data from php url ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://sml.com.pk/a/smldb.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data double des; double value; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); LAT=json_data.getDouble("TITLE"); LANG=json_data.getDouble("A"); } } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Vehicles Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } Here TITLE and A are my two columns of DB Table and i want to display them on gridview please any one help me to do this according to my current code. Here is my live url for data string http://sml.com.pk/a/smldb.php

    Read the article

  • Cascading items in a collection of a component

    - by mattcole
    I have a component which contains a collection. I can't seem to get NHibernate to persist items in the collection if I have the collection marked as Inverse. They will persist if I don't have Inverse on the collection, but I get an insert and then an update statement. My mapping is : m => m.Component(x => x.Configuration, c => { c.HasMany(x => x.ObjectiveTitleTemplates) .Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore) .AsSet() //.Inverse() .KeyColumns.Add("ObjectiveProcessInstanceId") .Cascade.AllDeleteOrphan(); }); Is there a way to get it working marking the collection as Inverse and therefore avoiding the extra insert? Thanks!

    Read the article

  • Java JRE vs GCJ

    - by Martijn Courteaux
    Hi, I have this results from a speed test I wrote in Java: Java real 0m20.626s user 0m20.257s sys 0m0.244s GCJ real 3m10.567s user 3m5.168s sys 0m0.676s So, what is the but of GCJ then? With this results I'm sure I'm not going to compile it with GCJ! I tested this on Linux, are the results in Windows maybe better than that? This was the code from the application: public static void main(String[] args) { String str = ""; System.out.println("Start!!!"); for (long i = 0; i < 5000000L; i++) { Math.sqrt((double) i); Math.pow((double) i, 2.56); long j = i * 745L; String string = new String(String.valueOf(i)); string = string.concat(" kaka pipi"); // "Kaka pipi" is a kind of childly call in Dutch. string = new String(string.toUpperCase()); if (i % 300 == 0) { str = ""; } else { str += Long.toHexString(i); } } System.out.println("Stop!!!"); }

    Read the article

  • Design Pattern for Changing Object

    - by user210757
    Is there a Design Pattern for supporting different permutations object? Version 1 public class myOjbect { public string field1 { get; set; } /* requirements: max length 20 */ public int field2 { get; set; } . . . public decimal field200 { get; set; } } Version 2 public class myObject { public string field1 { get; set; } /* requirements: max length 40 */ public int field2 { get; set; } . . . public double field200 { get; set; } /* changed data types */ . . ./* 10 new properties */ public double field210 { get; set; } } of course I could just have separate objects, but thought there might be a good pattern for this sort of thing.

    Read the article

  • How do I access abstract private data from derived class without friend or 'getter' functions in C++?

    - by John
    So, I am caught up in a dilemma right now. How am I suppose to access a pure abstract base class private member variable from a derived class? I have heard from a friend that it is possible to access it through the base constructor, but he didn't explain. How is it possible? There are some inherited classes from base class. Is there any way to gain access to the private variables ? class Base_button { private: bool is_vis; Rect rButton; public: // Constructors Base_button(); Base_button( const Point &corner, double height, double width ); // Destructor virtual ~ Base_button(); // Accessors virtual void draw() const = 0; bool clicked( const Point &click ) const; bool is_visible() const; // Mutators virtual void show(); virtual void hide(); void move( const Point &loc ); }; class Button : public Base_button { private: Message mButton; public: // Constructors Button(); Button( const Point &corner, const string &label ); // Acessors virtual void draw() const; // Mutators virtual void show(); virtual void hide(); }; I want to be able access Rect and bool in the base class from the subclass

    Read the article

  • Android: Calculator on showing 0 immediately after the dot

    - by pearmak
    I am now working on a calculator, and everything works fine except for decimal places. The calculator contains 2 displays actually, one is called fakedisplay for actual operations, and one is called Display, for presenting the desired format, ie adding commas. When pressing 12345.678, Display will follow fakedisplay and present as 12,345.678, but if i press 12345.009, the fakedisplay will work normally as 12345.009, but the Display stuck as 12,345 until 9 is pressed, and at that time it will show 12,345.009 normally. However, it is strange that when the user presses 0, there is no response, and until pressing 9, 009 will then immediately append. I know this arise from the parsing code, but based on this, how could I amend the following code? I really cannot think of any solution... Many thanks for all your advice! one.setOnClickListener(new View.OnClickListener() { if (str.length()<15) {Fakedisplay.append("1");} DecimalFormat myFormatter1 = new DecimalFormat("###,###,###,###.#################"); String str1=Fakedisplay.getText().toString(); String stripped1 = Double.valueOf(str1).toString(); stripped1 = myFormatter1.format(Double.valueOf(stripped1)); if (stripped1.endsWith(".0")) stripped1 = stripped1.substring(0, stripped1.length() - 2); Display.setText(stripped1);

    Read the article

  • How can I compare the performance of log() and fp division in C++?

    - by Ventzi Zhechev
    Hi, I’m using a log-based class in C++ to store very small floating-point values (as the values otherwise go beyond the scope of double). As I’m performing a large number of multiplications, this has the added benefit of converting the multiplications to sums. However, at a certain point in my algorithm, I need to divide a standard double value by an integer value and than do a *= to a log-based value. I have overloaded the *= operator for my log-based class and the right-hand side value is first converted to a log-based value by running log() and than added to the left-hand side value. Thus the operations actually performed are floating-point division, log() and floating-point summation. My question whether it would be faster to first convert the denominator to a log-based value, which would replace the floating-point division with floating-point subtraction, yielding the following chain of operations: twice log(), floating-point subtraction, floating-point summation. In the end, this boils down to whether floating-point division is faster or slower than log(). I suspect that a common answer would be that this is compiler and architecture dependent, so I’ll say that I use gcc 4.2 from Apple on darwin 10.3.0. Still, I hope to get an answer with a general remark on the speed of these two operators and/or an idea on how to measure the difference myself, as there might be more going on here, e.g. executing the constructors that do the type conversion etc. Cheers!

    Read the article

  • Do I need a spatial index in my database?

    - by Sanoj
    I am designing an application that needs to save geometric shapes in a database. I haven't choosen the database management system yet. In my application, all database queries will have an bounding box as input, and as output I want all shapes within that database. I know that databases with a spatial index is used for this kind of application. But in my application there will not be any queries of type "give me objects nearby x/y" or other more complex queries that are useful in a GIS application. I am planning of having a database without a spatial index and have queries looking like: SELECT * FROM shapes WHERE x < max_x AND x > min_x AND y < max_y AND y > min_y And have an index on the columns x (double) and y (double). As long I can see, I don't really need a database with an spatial index, howsoever my application is close to that kind of applications. And even if I would like to have nearby queries, then I could create a big enough bounding box around that point. Or will this lead to poor performance? Do I really need a spatial database? And when is a spatial index needed?

    Read the article

  • Sorting the output from XmlSerializer in C#

    - by prosseek
    In this post, I could get an XML file generated based on C# class. Can I reorder the XML elements based on its element? My code uses var ser = new XmlSerializer(typeof(Module)); ser.Serialize(WriteFileStream, report, ns); WriteFileStream.Close(); to get the XML file, but I need to have the XML file sorted based on a BlocksCovered variable. public class ClassInfo { public string ClassName; public int BlocksCovered; public int BlocksNotCovered; public double CoverageRate; public ClassInfo() {} public ClassInfo(string ClassName, int BlocksCovered, int BlocksNotCovered, double CoverageRate) { this.ClassName = ClassName; this.BlocksCovered = BlocksCovered; this.BlocksNotCovered = BlocksNotCovered; this.CoverageRate = CoverageRate; } } [XmlRoot("Module")] public class Module { [XmlElement("Class")] public List<ClassInfo> ClassInfoList; public int BlocksCovered; public int BlocksNotCovered; public string moduleName; public Module() { ClassInfoList = new List<ClassInfo>(); BlocksCovered = 0; BlocksNotCovered = 0; moduleName = ""; } } Module report = new Module(); ... TextWriter WriteFileStream = new StreamWriter(xmlFileName); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); var ser = new XmlSerializer(typeof(Module)); ser.Serialize(WriteFileStream, report, ns); WriteFileStream.Close();

    Read the article

  • ArrayIndexOutOfBoundsException trying to access data

    - by Eggy
    I am getting an array index out of bounds exception in the following code: for (int i=1; i<11; i++) { int a[][] = new int[10][3]; double LeftTrim = 1.0; double RightTrim = 1.0; a [i][0]=(int) (LeftTrim*((i)*25)); a [i][1]=(int) (RightTrim*((i)*25)); a [i][2]= 5000; //leftWheel, rightWheel, Milliseconds myf.setWheelVelocities(a[i][0], a[i][1], a[i][2]); JOptionPane.showMessageDialog(null, + (a [i][0] + a [i][1])/2 + "wheel velocities" + " | " + a [i][2] + " Milliseconds" + " Click OK to continue..."); } Every-time I reach the 9th increment Eclipse gives me the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10" I have to test the velocity up to 250, but when I reach 225 and I click 'Ok' on 'Click ok to continue..." this error shows up! Am I going out of the array bounds or something? Thank you!

    Read the article

  • Using pair in c++

    - by user1543957
    Can someone please tell why i am unable to compile the following program #include<iostream> #include<string> #include<cmath> #include<iostream> #include<cfloat> #define MOD 10000009 using namespace std; double distance(pair<int,int> p1,pair<int,int> p2) { double dist; dist = sqrt( (p1.first-p2.first)*(p1.first-p2.first) + (p1.second-p2.second)*(p1.second-p2.second) ); return(dist); } int main() { int N,i,j; cin >> N; pair<int,int> pi[N]; for(i=0;i<N;i++) { cin >> pi[i].first >> pi[i].second; } for(i=0;i<N;i++) { cout << pi[i].first << " "<< pi[i].second << endl; } distance(pi[0],pi[1]); // This line is giving error return 0; }

    Read the article

  • cuda 5.0 namespaces for contant memory variable usage

    - by Psypher
    In my program I want to use a structure containing constant variables and keep it on device all long as the program executes to completion. I have several header files containing the declaration of 'global' functions and their respective '.cu' files for their definitions. I kept this scheme because it helps me contain similar code in one place. e.g. all the 'device' functions required to complete 'KERNEL_1' are separated from those 'device' functions required to complete 'KERNEL_2' along with kernels definitions. I had no problems with this scheme during compilation and linking. Until I encountered constant variables. I want to use the same constant variable through all kernels and device functions but it doesn't seem to work. ########################################################################## CODE EXAMPLE ########################################################################### filename: 'common.h' -------------------------------------------------------------------------- typedef struct { double height; double weight; int age; } __CONSTANTS; __constant__ __CONSTANTS d_const; --------------------------------------------------------------------------- filename: main.cu --------------------------------------------------------------------------- #include "common.h" #include "gpukernels.h" int main(int argc, char **argv) { __CONSTANTS T; T.height = 1.79; T.weight = 73.2; T.age = 26; cudaMemcpyToSymbol(d_consts, &T, sizeof(__CONSTANTS)); test_kernel <<< 1, 16 >>>(); cudaDeviceSynchronize(); } --------------------------------------------------------------------------- filename: gpukernels.h --------------------------------------------------------------------------- __global__ void test_kernel(); --------------------------------------------------------------------------- filename: gpukernels.cu --------------------------------------------------------------------------- #include <stdio.h> #include "gpukernels.h" #include "common.h" __global__ void test_kernel() { printf("Id: %d, height: %f, weight: %f\n", threadIdx.x, d_const.height, d_const.weight); } When I execute this code, the kernel executes, displays the thread ids, but the constant values are displayed as zeros. How can I fix this?

    Read the article

  • What to set the scalar type to contain a byte []. Entity in MVC2

    - by Brad8118
    I'm trying out the EF 4.0 and using the Model first approach. I'd like to store images into the database and I'm not sure of the best type for the scalar in the entity. I currently have it(the image scalar type) setup as a binary. From what I have been reading the best way to store the image in the db is a byte[]. So I'm assuming that binary is the way to go. If there is a better way I'd switch. In my controller I have: //file from client to store in the db HttpPostedFileBase file = Request.Files[inputTagName]; if (file.ContentLength > 0) { keyToAdd.Image = new byte[file.ContentLength]; file.InputStream.Write(keyToAdd.Image, 0, file.ContentLength); } This builds fine but when I run it I get an exception writing the stream to keyToAdd.Image. The exception is something like: Method does not exist. Any ideas? Note that when using a EF 4.0 model first approach I only have int16, int32, double, string, decimal, binary, byte, DateTime, Double, Single, and SByte as available types. Thanks

    Read the article

  • Inheritance concept java..help

    - by max
    Hi everyone. I'd be very grateful if someone could help me to understand the inheritance concept in Java. Is the following code an example of that? I mean the class WavPanel is actually a subclass of JPanel which acts as a superclass. Is that correct? If so it means that "what JPanel has, also WavPanel but it is more specific since through its methods you can do something else". Am I wrong? thank you. Max import javax.swing.JPanel; class WavPanel extends JPanel { List<Byte> audioBytes; List<Line2D.Double> lines; public WavPanel() { super(); setBackground(Color.black); resetWaveform(); } public void resetWaveform() { audioBytes = new ArrayList<Byte>(); lines = new ArrayList<Line2D.Double>(); repaint(); } }

    Read the article

  • synchronizing reads to a java collection

    - by jeff
    so i want to have an arraylist that stores a series of stock quotes. but i keep track of bid price, ask price and last price for each. of course at any time, the bid ask or last of a given stock can change. i have one thread that updates the prices and one that reads them. i want to make sure that when reading no other thread is updating a price. so i looked at synchronized collection. but that seems to only prevent reading while another thread is adding or deleting an entry to the arraylist. so now i'm onto the wrapper approach: public class Qte_List { private final ArrayList<Qte> the_list; public void UpdateBid(String p_sym, double p_bid){ synchronized (the_list){ Qte q = Qte.FindBySym(the_list, p_sym); q.bid=p_bid;} } public double ReadBid(String p_sym){ synchronized (the_list){ Qte q = Qte.FindBySym(the_list, p_sym); return q.bid;} } so what i want to accomplish with this is only one thread can be doing anything - reading or updating an the_list's contents - at one time. am i approach this right? thanks.

    Read the article

  • c++ problem, maybe with types...

    - by Infinity
    Hi guys! I have a little problem in my code. The variables don't want to change their values. Can you say why? Here is my code: vector<coordinate> rocks(N); double angle; double x, y; // other code while (x > 1.0 || x < -1.0 || y > 1.0 || y < -1.0) { angle = rand() * 2.0 * M_PI; cout << angle << endl; cout << rocks[i - 1].x << endl; cout << rocks[i - 1].y << endl; x = rocks[i-1].x + r0 * cos(angle); y = rocks[i-1].y + r0 * sin(angle); cout << x << endl; cout << y << endl << endl; } // other code And the result on the console is: 6.65627e+09 0.99347 0.984713 1.09347 0.984713 1.16964e+09 0.99347 0.984713 1.09347 0.984713 As you see the values of x, y variables doesn't change and this while be an infinity loop. What's the problem? What do you think?

    Read the article

  • Const Discards Qualifers: C++

    - by user991673
    I'm using OpenGL to render camera perspectives, and a one point in my code I'm trying to take the direction of the light (shown here as type "Vector4") and multiply it by a matrix of type "Matrix4x4" that represents the Modelview transformation (sorry if this is not making any sense, this is for a school project, as such I'm still learning about this stuff) Anyway, my code goes as follows... Vector4 lightDirection = data->dir * follow->getModelviewMatrix().getInverse().getTranspose(); data->dir = lightDirection; setLight(*data); this give me the following error: passing 'const vec4<double>' as 'this' argument of 'vec4<T>& vec4<T>::operator=(const vec4<T>&)[with T = double]' discards qualifiers Again, much of this code is prewritten for the class (namely the vector and matrix types) but if someone could just help me decipher what the error means it would be much appreciated! I can give more information as needed. I figured 'data' or 'data-dir' were const, however I can find no mention of either of them to be. 'dir' is of type SceneLightData, and when its added on I'm doing this: void Scene::addLight(const SceneLightData &sceneLight) { SceneLightData light = sceneLight; m_lights.push_back(&light); } The error occurs on this line: data->dir = lightDirection; EDIT problem solved. thanks everyone! solution: void Scene::addLight(const SceneLightData &sceneLight) { SceneLightData* light = new SceneLightData; *light = sceneLight; m_lights.push_back(light); } and SceneLightData* data = m_lights[i]; data->dir = data->dir * follow->getModelviewMatrix().getInverse().getTranspose(); setLight(*data);

    Read the article

  • how do i make the app take correct input..?

    - by user1824343
    This is my windows app's one layout which converts Celsius to Fahrenheit. The problem is that when I try to input the temperature it shows some junk(for eg: if i enter '3' it displayin '3.0000009') and sometimes its even showing stack overflow exception. The output is also not shown properly : cel.text is the textbox for celsius. fahre.text is the textbox for fahrenheit. namespace PanoramaApp1 { public partial class FahretoCel : PhoneApplicationPage { public FahretoCel() { InitializeComponent(); } private void fahre_TextChanged(object sender, TextChangedEventArgs e) { if (fahre.Text != "") { try { double F = Convert.ToDouble(fahre.Text); cel.Text = "" + ((5.0/9.0) * (F - 32)) ; //this is conversion expression } catch (FormatException) { fahre.Text = ""; cel.Text = ""; } } else { cel.Text = ""; } } private void cel_TextChanged(object sender, TextChangedEventArgs e) { if (cel.Text != "") { try { Double c = Convert.ToDouble(cel.Text); fahre.Text = "" + ((c *(9.0 / 5.0 )) + 32); } catch (FormatException) { fahre.Text = ""; cel.Text = ""; } } else { fahre.Text = ""; } } } }

    Read the article

  • C++: Help with cin difference between Linux and Windows

    - by Krashman5k
    I have a Win32 console program that I wrote and it works fine. The program takes input from the user and performs some calculations and displays the output - standard stuff. For fun, I am trying to get the program to work on my Fedora box but I am running into an issue with clearing cin when the user inputs something that does not match my variable type. Here is the code in question: void CParameter::setPrincipal() { double principal = 0.0; cout << endl << "Please enter the loan principal: "; cin >> principal; while(principal <= 0) { if (cin.fail()) { cin.clear(); cin.ignore(INT_MAX, '\n'); } else { cout << endl << "Plese enter a number greater than zero. Please try again." << endl; cin >> principal; } } m_Parameter = principal; } This code works in Windows. For example, if the user tries to enter a char data type (versus double) then the program informs the user of the error, resets cin, and allows the user another opportunity to enter a valid value. When I move this code to Fedora, it compiles fine. When I run the program and enter an invalid data type, the while loop never breaks to allow the user to change the input. My questions are; how do I clear cin when invalid data is inputted in the Fedora environment? Also, how should I write this code so it will work in both environments (Windows & Linux)? Thanks in advance for your help!

    Read the article

  • Moq basic questions

    - by devoured elysium
    I made the following test for my class: var mock = new Mock<IRandomNumberGenerator>(); mock.Setup(framework => framework.Generate(0, 50)) .Returns(7.0); var rnac = new RandomNumberAverageCounter(mock.Object, 1, 100); rnac.Run(); double result = rnac.GetAverage(); Assert.AreEqual(result, 7.0, 0.1); The problem here was that I changed my mind about what range of values Generate(int min, int max) would use. So in Mock.Setup() I defined the range as from 0 to 50 while later I actually called the Generate() method with a range from 1 to 100. I ran the test and it failed. I know that that is what it's supposed to happen but I was left wondering if isn't there a way to launch an exception or throw in a message when trying to run the method with wrong params. Also, if I want to run this Generate() method 10 times with different values (let's say, from 1 to 10), will I have to make 10 mock setups or something, or is there a special method for it? The best I could think of is this (which isn't bad, I'm just asking if there is other better way): for (int i = 1; i < 10; ++i) { mock.Setup(framework => framework.Generate(1, 100)) .Returns((double)i); }

    Read the article

< Previous Page | 104 105 106 107 108 109 110 111 112 113 114 115  | Next Page >