Search Results

Search found 1594 results on 64 pages for 'initialization'.

Page 2/64 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Java: initialization problem with private-final-int-value and empty constructor

    - by HH
    $ javac InitInt.java InitInt.java:7: variable right might not have been initialized InitInt(){} ^ 1 error $ cat InitInt.java import java.util.*; import java.io.*; public class InitInt { private final int right; InitInt(){} public static void main(String[] args) { // I don't want to assign any value. // just initialize it, how? InitInt test = new InitInt(); System.out.println(test.getRight()); // later assiging a value } public int getRight(){return right;} } Initialization problem with Constructor InitInt{ // Still the error, "may not be initialized" // How to initialise it? if(snippetBuilder.length()>(charwisePos+25)){ right=charwisePos+25; }else{ right=snippetBuilder.length()-1; } }

    Read the article

  • Java: conditional initialization?

    - by HH
    Ruby has conditional initialization. Apparently, Java does not or does it? I try to write more succintly, to limit the range as small as possible. import java.io.*; import java.util.*; public class InitFor{ public static void main(String[] args){ for(int i=7,k=999;i+((String h="hello").size())<10;i++){} System.out.println("It should be: hello = "+h); } } Errors Press ENTER or type command to continue InitFor.java:8: ')' expected for(int i=7,k=999;i+((String h="hello").size())<10;i++){} ^

    Read the article

  • prevent using functions before initialization, constructors-like in C

    - by Hernán Eche
    This is the way I get to prevent funA,funB,funC, etc.. for being used before init #define INIT_KEY 0xC0DE //any number except 0, is ok static int initialized=0; int Init() { //many init task initialized=INIT_KEY; } int funA() { if (initialized!=INIT_KEY) return 1 //.. } int funB() { if (initialized!=INIT_KEY) return 1 //.. } int funC() { if (initialized!=INIT_KEY) return 1 //.. } The problem with this approach is that if some of those function is called within a loop so "if (initialized!=INIT_KEY)" is called again, and again, although it's not necessary. It's a good example of why constructors are useful haha, If it were an object I would be sure that when was created initialization was called, but in C, I don't know how to do it. Any other ideas are welcome!

    Read the article

  • boost.serialization and lazy initialization

    - by niXman
    i need to serialize directory tree. i have no trouble with this type: std::map< std::string, // string(path name) std::vector<std::string> // string array(file names in the path) > tree; but for the serialization the directory tree with the content i need other type: std::map< std::string, // string(path name) std::vector< // files array std::pair< std::string, // file name std::vector< // array of file pieces std::pair< // <<<<<<<<<<<<<<<<<<<<<< for this i need lazy initialization std::string, // piece buf boost::uint32_t // crc32 summ on piece > > > > > tree; how can i serialize the object of type "std::pair" in the moment of its serialization?

    Read the article

  • Java - Class type from inside static initialization block

    - by DutrowLLC
    Is it possible to get the class type from inside the static initialization block? This is a simplified version of what I currently have:: class Person extends SuperClass { String firstName; static{ // This function is on the "SuperClass": // I'd for this function to be able to get "Person.class" without me // having to explicitly type it in but "this.class" does not work in // a static context. doSomeReflectionStuff(Person.class); // IN "SuperClass" } } This is closer to what I am doing, which is to initialize a data structure that holds information about the object and its annotations, etc... Perhaps I am using the wrong pattern? public abstract SuperClass{ static void doSomeReflectionStuff( Class<?> classType, List<FieldData> fieldDataList ){ Field[] fields = classType.getDeclaredFields(); for( Field field : fields ){ // Initialize fieldDataList } } } public abstract class Person { @SomeAnnotation String firstName; // Holds information on each of the fields, I used a Map<String, FieldData> // in my actual implementation to map strings to the field information, but that // seemed a little wordy for this example static List<FieldData> fieldDataList = new List<FieldData>(); static{ // Again, it seems dangerous to have to type in the "Person.class" // (or Address.class, PhoneNumber.class, etc...) every time. // Ideally, I'd liken to eliminate all this code from the Sub class // since now I have to copy and paste it into each Sub class. doSomeReflectionStuff(Person.class, fieldDataList); } }

    Read the article

  • non-copyable objects and value initialization: g++ vs msvc

    - by R Samuel Klatchko
    I'm seeing some different behavior between g++ and msvc around value initializing non-copyable objects. Consider a class that is non-copyable: class noncopyable_base { public: noncopyable_base() {} private: noncopyable_base(const noncopyable_base &); noncopyable_base &operator=(const noncopyable_base &); }; class noncopyable : private noncopyable_base { public: noncopyable() : x_(0) {} noncopyable(int x) : x_(x) {} private: int x_; }; and a template that uses value initialization so that the value will get a known value even when the type is POD: template <class T> void doit() { T t = T(); ... } and trying to use those together: doit<noncopyable>(); This works fine on msvc as of VC++ 9.0 but fails on every version of g++ I tested this with (including version 4.5.0) because the copy constructor is private. Two questions: Which behavior is standards compliant? Any suggestion of how to work around this in gcc (and to be clear, changing that to T t; is not an acceptable solution as this breaks POD types). P.S. I see the same problem with boost::noncopyable.

    Read the article

  • C++: Construction and initialization order guarantees

    - by Helltone
    Hi, I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z and W. The main function instantiates an object of class X. X contains an object of class Y, and derives from class Z, so both constructors will be called. Additionally, the const char* parameter passed to X's constructor will be implicitly converted to W, so W's constructor must also be called. What are the guarantees the C++ standard gives on the order of the calls to the copy constructors? Or, equivalently, this program is allowed to print? #include <iostream> class Z { public: Z() { std::cout << "Z" << std::endl; } }; class Y { public: Y() { std::cout << "Y" << std::endl; } }; class W { public: W(const char*) { std::cout << "W" << std::endl; } }; class X : public Z { public: X(const W&) { std::cout << "X" << std::endl; } private: Y y; }; int main(int, char*[]) { X x("x"); return 0; }

    Read the article

  • why does array initialization in function other than main is temporary? [on hold]

    - by shafeeq
    This is the code in which i initialize array "turn[20]" in main as well as in function "checkCollisionOrFood()",the four values turn[0],turn[1],turn[2],turn[3] are initialized to zero in main function,rest are being intialized in "checkCollisionOrFood()".This is where fault starts.when i initialize turn[4]=0 in "checkCollisionOrFood()" and then access it anywhere,it remains 0 in any function,but! when i initialize next turn[] i.e turn[5],the value of turn[4] gets depleted .i.e turn[4] have garbage value.turn[20] is global variable,its index"head" is also global.I'm stuck.Plz help me get out of it.Ishall be highly obliged for this act of kindness.This is my excerpt of code unsigned short checkCollisionOrFood(){ head=(head+1)%20; if(turn[head-1]==0){ turn[head]=0; /this is where turn[] is iniliazized and if i access turn[head] here i.e just after iniliazition then it gives correct value but if i access its previous value means turn[head-1]then it gives garbage value/ rowHead=(rowHead+1)%8; if(!(address[colHead]&(1<<rowHead)))return 1; else if((address[colHead]&(1<<rowHead))&& (!((colHead==foody)&&(rowHead==foodx))))gameOver(); else return 0; } if(turn[head-1]==1){ turn[head]=1; colHead=(colHead+1)%8; if(!(address[colHead]&(1<<rowHead)))return 1; else if((address[colHead]&(1<<rowHead))&& (!((colHead==foody)&&(rowHead==foodx))))gameOver(); else return 0; } } void main(void) { turn[0]=0;turn[1]=0;turn[2]=0;turn[3]=0; /these values of turn[] are not changed irrespective of where they are accessed./ while (1) { if(checkCollisionOrFood()) { PORTB=(address[colHead] |=1<<rowHead); turnOffTail(); blink(); } else { PORTB=address[colHead]; createFood(); blink(); } } } Plz help me.

    Read the article

  • Array variable initialization error in Java

    - by trinity
    Hello I am trying to write a Java program that reads an input file consisting of URLs, extracts tokens from these, and keeps track of how many times each token appears in the file. I've written the following code: import java.io.*; import java.net.*; public class Main { static class Tokens { String name; int count; } public static void main(String[] args) { String url_str,host; String htokens[]; URL url; boolean found=false; Tokens t[]; int i,j,k; try { File f=new File("urlfile.txt"); FileReader fr=new FileReader(f); BufferedReader br=new BufferedReader(fr); while((url_str=br.readLine())!=null) { url=new URL(url_str); host=url.getHost(); htokens=host.split("\\.|\\-|\\_|\\~|[0-9]"); for(i=0;i<htokens.length;i++) { if(!htokens[i].isEmpty()) { for(j=0;j<t.length;j++) { if(htokens[i].equals(t[j].name)) { t[j].count++; found=true; } } if(!found) { k=t.length; t[k].name=htokens[i]; t[k].count=1; } } } System.out.println(t.length + "class tokens :"); for(i=0;i<t.length;i++) { System.out.println( "name :"+t[i].name+" frequency :"+t[i].count); } } br.close(); fr.close(); } catch(Exception e) { System.out.println(e); } } } But when I run it, it says: variable t not initialized.. What should I do to set it right?

    Read the article

  • class array variable initialization error in java

    - by trinity
    Hello I am trying to write a java program that reads an input file consisting of URLs , extracts tokens from these , and accordingly insert into : class Tokens { String name ; int count ; } , where name is the name of every unique token , and count is the frequency of that token in the URLs file..I've written the following code : import java.io.*; import java.net.*; public class Main { static class Tokens { String name; int count; } public static void main(String[] args) { String url_str,host; String htokens[]; URL url; boolean found=false; Tokens t[]; int i,j,k; try { File f=new File("urlfile.txt"); FileReader fr=new FileReader(f); BufferedReader br=new BufferedReader(fr); while((url_str=br.readLine())!=null) { url=new URL(url_str); host=url.getHost(); htokens=host.split("\\.|\\-|\\_|\\~|[0-9]"); for(i=0;i<htokens.length;i++) { if(!htokens[i].isEmpty()) { for(j=0;j<t.length;j++) { if(htokens[i].equals(t[j].name)) { t[j].count++; found=true; } } if(!found) { k=t.length; t[k].name=htokens[i]; t[k].count=1; } } } System.out.println(t.length + "class tokens :"); for(i=0;i<t.length;i++) { System.out.println("name :"+t[i].name+" frequency :"+t[i].count); } } br.close(); fr.close(); } catch(Exception e) { System.out.println(e); } } } But when i run it , it says : variable t not initialized.. What should i do to set it right ?

    Read the article

  • Basic C++ Speed (initialization vs adding) and comparison speed

    - by seld
    I was curious if anyone knows which of the following executes faster (I know this seems like a weird question but I'm trying to shave as much time and resources as possible off my program.) int i; i+=1; or int i; i=1; and I also was curious about which comparison is faster: //given some integer i // X is some constant i < X+1 or i<=X

    Read the article

  • WinForms Load Event / Static Initialization Strangeness

    - by Eric J.
    Background I'm troubleshooting an WinForms 2.0 program that's already been burned to CD for distribution to an internet-challenged target audience. Some users are experiencing a fatal error that I can reproduce locally. Reproducing the Error I get the fatal error when I log into my Vista box using a standard user that I just created, even if I run the program as administrator. I do not get the fatal error when I log in as local administrator. I'm not sure that being administrator is necessarily the trigger (since runas did not help). I have reproduced this half a dozen times under each account with consistent results. The faulty code Base.cs (base class for several user controls, only one of which is shown on first screen) private void BaseWindow_Load(object sender, EventArgs e) { // This message shown once in both cases MessageBox.Show("BaseWindow_Load for " + this.GetType().FullName); SkinManager.ApplySkin(this); } SkinManager.cs private static Skin skin = null; public static void ApplySkin(UserControl applyTo) { if (skin == null) { skin = new Skin(SkinsDirectory, "Default"); } } Skin.cs internal Skin(string skinPath, string skinName) { config = SkinConfig.Load(path); } SkinConfig.cs public static SkinConfig Load(string path) { // This message shown only once running as Admin but twice running as standard user System.Windows.Forms.MessageBox.Show("@1"); // !!! LOCK path HERE !!! } A user control loads on the first form, which triggers a call to SkinManager.ApplySkin, which checks if skin is null and, if so assigns it (without thread synchronization or recursion protection), which ultimately causes a file to be opened. When logged in as local admin, that sequence completes just fine. When logged in as my test standard user, ApplySkin is always called a second time while skin is still null, causing a second attempt to load, causing the file to be locked on the second attempt. The error handling is draconian at this point and the program terminates. The Question While this code can be easily fixed, I would like to understand why the error is happening only in some cases.

    Read the article

  • Java: define terms initialization, declaration and assignment

    - by HH
    I find the defs circular statements, the subjects are defined by their verbs but the verbs are undefined! So how do you define them? The question is central to understand the term final, related. The Circular Definitions itialization: to initilise a variable. It can be can be done at the time of declaration. assignment: to assign value to a variable. It can be done anywhere. declaration: to declare value to a variable.

    Read the article

  • iPhone -- initialization partly by NSKeyedUnarchiver and partly by other means

    - by William Jockusch
    I have an object myObj, which is an instance of a class MyClass. Some of its instance variables always have their initial values passed in by the calling code. Other instance variables will be initialized in one of two ways. For an instanceArray of type NSMutableArray, the possibilities are either instanceArray = [[NSMutableArray alloc]init]; or instanceArray = [someKeyedUnarchiver decodeObjectForKey: kInstanceArrayKey]; The calling code should determine which of the above will be used. Any particular design pattern I should prefer?

    Read the article

  • Java ArrayList initialization

    - by Jonathan
    I am aware that you can initialize an array during instantiation as follows: String[] names = new String[] {"Ryan", "Julie", "Bob"}; Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()? Thanks, Jonathan

    Read the article

  • SD card initialization using SPI interface

    - by Tobias
    I get invalid response Codes from my SD Card(CMD8, CMD55, CMD41) Init routine: SDCS = 1; // MMC deaktiviert SPI1CON1bits.SMP = 0; SPI1CON1bits.CKE = 1; SPI1CON1bits.MSTEN = 1; SPI1CON1bits.CKP = 0; SPI1STATbits.SPIEN = 1; for(i=0;i<10;i++) SPI(0xFF); // RESET unsigned char rr=Command(CMD0,0); SDCS=1; // MMC deactivated /*OK response == 1*/ r=Command(CMD8,0); // check voltage SDCS=1; /* response == 0xC1 ?!? */ r = Command(CMD58,0); // READ_OCR unsigned char ocr1 = SPI(0xFF); unsigned char ocr2 = SPI(0xFF); unsigned char ocr3 = SPI(0xFF); unsigned char ocr4 = SPI(0xFF); unsigned char ocr5 = SPI(0xFF); /* r = 0xF8; ?!? ocr1 = 0x0F; ocr2 = 0xFF; ocr3 = 0xFF; ocr4 = 0xFF; ocr5 = 0xFF; */ SDCS=1; // INIT unsigned char rrr = 0; i=10000; do { rrr=Command(55,0); // Next is APP CMD SDCS=1; if(r) break; }while(--i>0); /* OK response == 1 */ // APP CMD 41 with OCR = 0x0F?? You can read the response codes in the comments. Is it possible the response code to CMD8 is 0xC1? Bit 7 should be 0, right? Is it a hardware error?

    Read the article

  • Initialization of std::vector<unsigned int> with a list of consecutive unsigned integers

    - by Thomas
    I want to use a special method to initialize a std::vector<unsigned int> which is described in a C++ book I use as a reference (the German book 'Der C++ Programmer' by Ulrich Breymann, in case that matters). In that book is a section on sequence types of the STL, referring in particular to list, vector and deque. In this section he writes that there are two special constructors of such sequence types, namely, if Xrefers to such a type, X(n, t) // creates a sequence with n copies of t X(i, j) // creates a sequence from the elements of the interval [i, j) I want to use the second one for an interval of unsigned int, that is std::vector<unsigned int> l(1U, 10U); to get a list initialized with {1,2,...,9}. What I get, however, is a vector with one unsigned int with value 10 :-| Does the second variant exist, and if yes, how do I force that it is called?

    Read the article

  • Initialization of an ArrayList in one line.

    - by Macarse
    I am willing to create a list of options to test something. I was doing: ArrayList<String> places = new ArrayList<String>(); places.add("Buenos Aires"); places.add("Córdoba"); places.add("La Plata"); I refactor the code doing: ArrayList<String> places = new ArrayList<String>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata")); Is there a better way of doing this? Thanks for reading!

    Read the article

  • DRY Ruby Initialization with Hash Argument

    - by ktex
    I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. What I end up doing is something like the following: class Example PROPERTIES = [:name, :age] PROPERTIES.each { |p| attr_reader p } def initialize(args) PROPERTIES.each do |p| self.instance_variable_set "@#{p}", args[p] if not args[p].nil? end end end Is there no more idiomatic way to achieve this? The throw-away constant and the symbol to string conversion seem particularly egregious.

    Read the article

  • Is this pointer initialization necessary?

    - by bstullkid
    Lets say I have the following: CHARLINK * _init_link(CHARLINK **link) { short i; (*link)->cl = (CHARLINK **) calloc(NUM_CHARS, sizeof(CHARLINK *)); for (i = 0; i < NUM_CHARS; i++) (*link)->cl[i] = NULL; return (*link); } Is the loop to initialize each element to NULL necessary or are they automatically NULL from calloc?

    Read the article

  • Java: initialization problem, cannot print "assigned" values from arrayList

    - by HH
    $ javac ArrayListTest.java $ java ArrayListTest $ cat ArrayListTest.java import java.io.*; import java.util.*; public class ArrayListTest{ public static void main(String[] args) { try { String hello ="oeoaseu oeu hsoae sthoaust hoaeut hoasntu"; ArrayList<String> appendMe = null; for(String s : hello.split(" ")) appendMe.add(s+" "); for(String s : appendMe) System.out.println(s); //WHY DOES IT NOT PRINT? }catch(Exception e){ } } }

    Read the article

  • Characteristics of an Initialization Vector

    - by Jamie Chapman
    I'm by no means a cryptography expert, I have been reading a few questions around Stack Overflow and on Wikipedia but nothing is really 'clear cut' in terms of defining an IV and it's usage. Points I have discovered: An IV is pre-pended to a plaintext message in order to strengthen the encryption The IV is truely random Each message has it's own unique IV Timestamps and cryptographic hashes are sometimes used instead of random values, but these are considered to be insecure as timestamps can be predicted One of the weaknesses of WEP (in 802.11) is the fact that the IV will reset after a specific amount of encryptions, thus repeating the IV I'm sure there are many other points to be made, what have I missed? (or misread!)

    Read the article

  • C++ Constructor initialization list strangeness

    - by Andy
    I have always been a good boy when writing my classes, prefixing all member variables with m_: class Test { int m_int1; int m_int2; public: Test(int int1, int int2) : m_int1(int int1), m_int2(int int2) {} }; void main() { Test t(10, 20); // Just an example } However, recently I forgot to do that and ended up writing: class Test { int int1; int int2; public: // Very questionable, but of course I meant to assign ::int1 to this->int1! Test(int int1, int int2) : int1(int1), int2(int2) {} }; Believe it or not, the code compiled with no errors/warnings and the assignments took place correctly! It was only when doing the final check before checking in my code when I realised what I had done. My question is: why did my code compile? Is something like that allowed in the C++ standard, or is it simply a case of the compiler being clever? In case you were wondering, I was using Visual Studio 2008 Thank you.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >