Search Results

Search found 3887 results on 156 pages for 'pointer arithmetic'.

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

  • How to store a function pointer in C#

    - by Joshua
    Let's say I want to store a group of function pointers in a List<(*func), and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), object[] params could I call the func with the parameters? How would I do this?

    Read the article

  • C++ vector pointer/reference problem

    - by sub
    Please take a look at this example: #include <iostream> #include <vector> #include <string> using namespace std; class mySubContainer { public: string val; }; class myMainContainer { public: mySubContainer sub; }; void doSomethingWith( myMainContainer &container ) { container.sub.val = "I was modified"; } int main( ) { vector<myMainContainer> vec; /** * Add test data */ myMainContainer tempInst; tempInst.sub.val = "foo"; vec.push_back( tempInst ); tempInst.sub.val = "bar"; vec.push_back( tempInst ); // 1000 lines of random code here int i; int size = vec.size( ); myMainContainer current; for( i = 0; i < size; i ++ ) { cout << i << ": Value before='" << vec.at( i ).sub.val << "'" << endl; current = vec.at( i ); doSomethingWith( current ); cout << i << ": Value after='" << vec.at( i ).sub.val << "'" << endl; } system("pause");//i suck } A hell lot of code for an example, I know. Now so you don't have to spend years thinking about what this [should] do[es]: I have a class myMainContainer which has as its only member an instance of mySubContainer. mySubContainer only has a string val as member. So I create a vector and fill it with some sample data. Now, what I want to do is: Iterate through the vector and make a separate function able to modify the current myMainContainer in the vector. However, the vector remains unchanged as the output tells: 0: Value before='foo' 0: Value after='foo' 1: Value before='bar' 1: Value after='bar' What am I doing wrong? doSomethingWith has to return void, I can't let it return the modified myMainContainer and then just overwrite it in the vector, that's why I tried to pass it by reference as seen in the doSomethingWith definition above.

    Read the article

  • How to check if a pointer is null in C++ Visual 2010

    - by mariomario
    I am having problems here if I want to check if eerste points to nothing i get Blockquote Unhandled exception at 0x003921c6 in Bank.exe: 0xC0000005: Access violation reading location 0xccccccd0. and i am kinda wondering why he justs skips the if statement or doens't stop when the object eerste points to nothing Bank::Bank() { LijstElement *eerste = NULL; LijstElement *laatste = NULL; } Rekening * Bank::getRekening(int rekNr) { if(NULL != eerste) { LijstElement *nummer = eerste; while(nummer->volgende!= NULL) { Rekening *een = nummer->getRekening(); if(een->getRekNr()==rekNr) { return een; } else { nummer = nummer->volgende; } } } return NULL; }

    Read the article

  • Allocating memory for a array to char pointer

    - by nunos
    The following piece of code gives a segmentation fault when allocating memory for the last arg. What am I doing wrong? Thanks. int n_args = 0, i = 0; while (line[i] != '\0') { if (isspace(line[i++])) n_args++; } for (i = 0; i < n_args; i++) command = malloc (n_args * sizeof(char*)); char* arg = NULL; arg = strtok(line, " \n"); while (arg != NULL) { arg = strtok(NULL, " \n"); command[i] = malloc ( (strlen(arg)+1) * sizeof(char) ); strcpy(command[i], arg); i++; } Thanks.

    Read the article

  • C++ pointer to different array

    - by begun
    Assume I have an array a and an array b. Both have the same type and size but different values. Now I create 3 or so pointers that point to different elements in a, you could say a[ 0 ], a[ 4 ] and a[ 13 ]. Now if I overwrite a with b via a=b - Where will the pointers point? Do the pointers still point to their original positions in a but the values they point to are now those of b?

    Read the article

  • C++: Copying to dereferenced pointer...

    - by bbb
    Hi. I currently have a weird problem with a program segfaulting but im not able to spot the error. I think the problem boils down to this. struct S {int a; vector<sometype> b;} S s1; // fill stuff into a and b S* s2 = new S(); *s2 = s1; Could it be that the final copying is illegal in some way? Im really confused right now... Thanks

    Read the article

  • Pointer-like behavior in Java

    - by Shmoo
    I got the following: class A{ int foo; } class B extends A{ public void bar(); } I got a instance of A and want to convert it to an instance of B without losing the reference to the variable foo. For example: A a = new A(); a.foo = 2; B b = a; <-- what I want to do. //use b b.foo = 3; //a.foo should now be 3 Thanks for any help!

    Read the article

  • What's the best way to do base36 arithmetic in perl?

    - by DVK
    What's the best way to do base36 arithmetic in Perl? To be more specific, I need to be able to do the following: Operate on positive N-digit numbers in base 36 (e.g. digits are 0-9 A-Z) N is finite, say 9 Provide basic arithmetic, at the very least the following 3: Addition (A+B) Subtraction (A-B) Whole division, e.g. floor(A/B). Strictly speaking, I don't really need a base10 conversion ability - the numbers will 100% of time be in base36. So I'm quite OK if the solution does NOT implement conversion from base36 back to base10 and vice versa. I don't much care whether the solution is brute-force "convert to base 10 and back" or converting to binary, or some more elegant approach "natively" performing baseN operations (as stated above, to/from base10 conversion is not a requirement). My only 3 considerations are: It fits the minimum specifications above It's "standard". Currently we're using and old homegrown module based on base10 conversion done by hand that is buggy and sucks. I'd much rather replace that with some commonly used CPAN solution instead of re-writing my own bicycle from scratch, but I'm perfectly capable of building it if no better standard possibility exists. It must be fast-ish (though not lightning fast). Something that takes 1 second to sum up 2 9-digit base36 numbers is worse than anything I can roll on my own :) P.S. Just to provide some context in case people decide to solve my XY problem for me in addition to answering the technical question above :) We have a fairly large tree (stored in DB as a bunch of edges), and we need to superimpose order on a subset of that tree. The tree dimentions are big both depth- and breadth- wise. The tree is VERY actively updated (inserts and deletes and branch moves). This is currently done by having a second table with 3 columns: parent_vertex, child_vertex, local_order, where local_order is an 9-character string built of A-Z0-9 (e.g. base 36 number). Additional considerations: It is required that the local order is unique per child (and obviously unique per parent), Any complete re-ordering of a parent is somewhat expensive, and thus the implementation is to try and assign - for a parent with X children - the orders which are somewhat evenly distributed between 0 and 36**10-1, so that almost no tree inserts result in a full re-ordering.

    Read the article

  • Time passage arithmetic explanation

    - by Cyber Axe
    I ported this from http://www.effectgames.com/effect/article.psp.html/joe/Old_School_Color_Cycling_with_HTML5 some time ago. However i'm now wanting to modify it for the purpose of changing it from floating point to fixed point maths for enhanced efficiency (for those who are going to talk about premature optimization and what not, i want to have my entire engine in fixed point both as a learning process for me and so i can port code more easily to systems in the future that dont have native floating points such as arm cpus) My initial conversion to fixed points just resulted in the cycling stuck on either the first or last frame of cycling. Plus it would be nice to understand better how it works so i can add more options and so forth in the future, my maths however sucks and the comments are limited so i don't really know how the maths work for determining the frame it shoud use (cycleAmount) I was also a beginner when i ported it as i had no idea between floating points and integers and what not. So in summary my question is, can anyone give an explination of the arithmatic used for determining the cycleAmount (which determings the "frame" of the cycle) This is the working floating point maths version of the code: public final void cycle(Colour[] sourceColours, double timeNow, double speedAdjust) { // Cycle all animated colour ranges in palette based on timestamp. sourceColours = sourceColours.clone(); int cycleSize; double cycleRate; double cycleAmount; Cycle cycle; for (int i = 0, len = cycles.length; i < len; ++i) { cycle = cycles[i]; cycleSize = (cycle.HIGH - cycle.LOW) + 1; cycleRate = cycle.RATE / (int) (CYCLE_SPEED / speedAdjust); cycleAmount = 0; if (cycle.REVERSE < 3) { // Standard Cycle cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize); if (cycle.REVERSE < 1) { cycleAmount = cycleSize - cycleAmount; // If below 1 make sure its not reversed. } } else if (cycle.REVERSE == 3) { // Ping-Pong cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize << 1); if (cycleAmount >= cycleSize) { cycleAmount = (cycleSize * 2) - cycleAmount; } } else if (cycle.REVERSE < 6) { // Sine Wave cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize); cycleAmount = Math.sin((cycleAmount * 3.1415926 * 2) / cycleSize) + 1; if (cycle.REVERSE == 4) { cycleAmount *= (cycleSize / 4); } else if (cycle.REVERSE == 5) { cycleAmount *= (cycleSize >> 1); } } if (cycle.REVERSE == 2) { reverseColours(sourceColours, cycle); } if (USE_BLEND_SHIFT) { blendShiftColours(sourceColours, cycle, cycleAmount); } else { shiftColours(sourceColours, cycle, cycleAmount); } if (cycle.REVERSE == 2) { reverseColours(sourceColours, cycle); } } colours = sourceColours; } // This utility function allows for variable precision floating point modulus. private double DFLOAT_MOD(final double d, final double b) { return (Math.floor(d * PRECISION) % Math.floor(b * PRECISION)) / PRECISION; }

    Read the article

  • Is it possible to pass arithmetic operators to a method in java?

    - by drJames
    Right now I'm going to have to write a method that looks like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { if (Operator.equals("+")) { return String.valueOf(Operand1 + Operand2); } else if (Operator.equals("-")) { return String.valueOf(Operand1 - Operand2); } else if (Operator.equals("*")) { return String.valueOf(Operand1 * Operand2); } else { return "error..."; } } It would be nice if I could write the code more like this: public String Calculate(String Operator, Double Operand1, Double Operand2) { return String.valueOf(Operand1 Operator Operand2); } So Operator would replace the Arithmetic Operators (+, -, *, /...) Does anyone know if something like this is possible in java?

    Read the article

  • Mouse pointer size inconsistent

    - by charon00
    Since installing Ubuntu 12.04, I've been having a problem with the mouse pointer size. On the desktop, it is quite a bit larger than it should be (24), though the different cursors (editing text, hyperlink hand, etc) are correct. The size changes to the correct size when the pointer is over some application windows (GVim, Netbeans, Firefox), but then changes back once it is moved out of the window. There was a similar question here, but the Xdefaults solution did not work for me, and I didn't want to try the one requiring editing the icon image. In addition, I've tried changing the cursor theme using sudo update-alternatives --config x-cursor-theme as well as using the dconf-editor, but though I can change the theme, the size issue remains. In case it's relevant, I'm running on a dual-screen setup with monitor sizes of 2560x1600 and 1920x1080, using the NVidia video driver. Is there another way to control pointer size, or a setting that might be messing it up? EDIT: These are the values/options I have for update-alternatives and in dconf-editor. I'm now wondering if Netbeans and Firefox are making the mouse pointer smaller than it should be, but I'm not sure how big 24 should be... update-alternatives: Selection Path Priority Status ------------------------------------------------------------ 0 /usr/share/icons/DMZ-White/cursor.theme 90 auto mode 1 /etc/X11/cursors/core.theme 30 manual mode 2 /etc/X11/cursors/handhelds.theme 20 manual mode 3 /etc/X11/cursors/redglass.theme 20 manual mode 4 /etc/X11/cursors/whiteglass.theme 20 manual mode * 5 /usr/share/icons/DMZ-Black/cursor.theme 30 manual mode 6 /usr/share/icons/DMZ-White/cursor.theme 90 manual mode dconf-editor: I can't post the image since I'm a new user but the cursor-size is set to 24 and the cursor-theme is DMZ-Black.

    Read the article

  • generic programming in C with void pointer.

    - by Nyan
    Hi everyone, even though it is possible to write generic code in C using void pointer(generic pointer), I find that it is quite difficult to debug the code since void pointer can take any pointer type without warning from compiler. (e.g function foo() take void pointer which is supposed to be pointer to struct, but compiler won't complain if char array is passed.) What kind of approach/strategy do you all use when using void pointer in C?

    Read the article

  • Gnome3 pointer barrier not working with dual monitors

    - by Nathan
    I have a dual monitor setup using Gnome3. Misc Info : In the past I used Fedora, there was a pointer barrier between my two monitors in the upper left corner so that I can hit the hot corner when moving from the right monitor to the left monitor. Problem : However, with my new Ubuntu installation, the barrier no longer exists and my mouse pointer glides straight to the next screen. This makes that hot corner nearly useless. I've looked around, messed with the values in /usr/share/gnome-shell/js/ui/layout.js, but I can't figure out how to make the pointer barrier work. may someone suggest hot to get the full utilization of hot cornet.

    Read the article

  • Array Multiplication and Division

    - by Narfanator
    I came across a question that (eventually) landed me wondering about array arithmetic. I'm thinking specifically in Ruby, but I think the concepts are language independent. So, addition and subtraction are defined, in Ruby, as such: [1,6,8,3,6] + [5,6,7] == [1,6,8,3,6,5,6,7] # All the elements of the first, then all the elements of the second [1,6,8,3,6] - [5,6,7] == [1,8,3] # From the first, remove anything found in the second and array * scalar is defined: [1,2,3] * 2 == [1,2,3,1,2,3] But What, conceptually, should the following be? None of these are (as far as I can find) defined: Array x Array: [1,2,3] * [1,2,3] #=> ? Array / Scalar: [1,2,3,4,5] / 2 #=> ? Array / Scalar: [1,2,3,4,5] % 2 #=> ? Array / Array: [1,2,3,4,5] / [1,2] #=> ? Array / Array: [1,2,3,4,5] % [1,2] #=> ? I've found some mathematical descriptions of these operations for set theory, but I couldn't really follow them, and sets don't have duplicates (arrays do). Edit: Note, I do not mean vector (matrix) arithmetic, which is completely defined. Edit2: If this is the wrong stack exchange, tell me which is the right one and I'll move it. Edit 3: Add mod operators to the list. Edit 4: I figure array / scalar is derivable from array * scalar: a * b = c => a = b / c [1,2,3] * 3 = [1,2,3]+[1,2,3]+[1,2,3] = [1,2,3,1,2,3,1,2,3] => [1,2,3] = [1,2,3,1,2,3,1,2,3] / 3 Which, given that programmer's division ignore the remained and has modulus: [1,2,3,4,5] / 2 = [[1,2], [3,4]] [1,2,3,4,5] % 2 = [5] Except that these are pretty clearly non-reversible operations (not that modulus ever is), which is non-ideal. Edit: I asked a question over on Math that led me to Multisets. I think maybe extensible arrays are "multisets", but I'm not sure yet.

    Read the article

  • How to handle failure to release a resource which is contained in a smart pointer?

    - by cj
    How should an error during resource deallocation be handled, when the object representing the resource is contained in a shared pointer? Smart pointers are a useful tool to manage resources safely. Examples of such resources are memory, disk files, database connections, or network connections. // open a connection to the local HTTP port boost::shared_ptr<Socket> socket = Socket::connect("localhost:80"); In a typical scenario, the class encapsulating the resource should be noncopyable and polymorphic. A good way to support this is to provide a factory method returning a shared pointer, and declare all constructors non-public. The shared pointers can now be copied from and assigned to freely. The object is automatically destroyed when no reference to it remains, and the destructor then releases the resource. /** A TCP/IP connection. */ class Socket { public: static boost::shared_ptr<Socket> connect(const std::string& address); virtual ~Socket(); protected: Socket(const std::string& address); private: // not implemented Socket(const Socket&); Socket& operator=(const Socket&); }; But there is a problem with this approach. The destructor must not throw, so a failure to release the resource will remain undetected. A common way out of this problem is to add a public method to release the resource. class Socket { public: virtual void close(); // may throw // ... }; Unfortunately, this approach introduces another problem: Our objects may now contain resources which have already been released. This complicates the implementation of the resource class. Even worse, it makes it possible for clients of the class to use it incorrectly. The following example may seem far-fetched, but it is a common pitfall in multi-threaded code. socket->close(); // ... size_t nread = socket->read(&buffer[0], buffer.size()); // wrong use! Either we ensure that the resource is not released before the object is destroyed, thereby losing any way to deal with a failed resource deallocation. Or we provide a way to release the resource explicitly during the object's lifetime, thereby making it possible to use the resource class incorrectly. There is a way out of this dilemma. But the solution involves using a modified shared pointer class. These modifications are likely to be controversial. Typical shared pointer implementations, such as boost::shared_ptr, require that no exception be thrown when their object's destructor is called. Generally, no destructor should ever throw, so this is a reasonable requirement. These implementations also allow a custom deleter function to be specified, which is called in lieu of the destructor when no reference to the object remains. The no-throw requirement is extended to this custom deleter function. The rationale for this requirement is clear: The shared pointer's destructor must not throw. If the deleter function does not throw, nor will the shared pointer's destructor. However, the same holds for other member functions of the shared pointer which lead to resource deallocation, e.g. reset(): If resource deallocation fails, no exception can be thrown. The solution proposed here is to allow custom deleter functions to throw. This means that the modified shared pointer's destructor must catch exceptions thrown by the deleter function. On the other hand, member functions other than the destructor, e.g. reset(), shall not catch exceptions of the deleter function (and their implementation becomes somewhat more complicated). Here is the original example, using a throwing deleter function: /** A TCP/IP connection. */ class Socket { public: static SharedPtr<Socket> connect(const std::string& address); protected: Socket(const std::string& address); virtual Socket() { } private: struct Deleter; // not implemented Socket(const Socket&); Socket& operator=(const Socket&); }; struct Socket::Deleter { void operator()(Socket* socket) { // Close the connection. If an error occurs, delete the socket // and throw an exception. delete socket; } }; SharedPtr<Socket> Socket::connect(const std::string& address) { return SharedPtr<Socket>(new Socket(address), Deleter()); } We can now use reset() to free the resource explicitly. If there is still a reference to the resource in another thread or another part of the program, calling reset() will only decrement the reference count. If this is the last reference to the resource, the resource is released. If resource deallocation fails, an exception is thrown. SharedPtr<Socket> socket = Socket::connect("localhost:80"); // ... socket.reset();

    Read the article

  • Doing arithmetic and passing it to the next command

    - by neurolysis
    I know how to do this in /bin/sh, but I'm struggling a bit in Windows. I know you can do arithmetic on 32-bit signed integers with SET /a 2+2 4 But how do I pass this to the next command? For example, the process I want to perform is as follows. Consumer editions of Windows have no native automated sleep function (I believe?) -- the best way to perform a sleep is to use PING in association with the -n switch to get that many seconds, minus one, of sleep. The following command is effective for a silent sleep: PING localhost -n 3 > NUL But I want to alias this into a sleep command. I'd like to have it elegant so that you enter the actual number of seconds you want to sleep after the command, right now I can do DOSKEY SLEEP=PING 127.0.0.1 -n $1 > NUL Which works, but it's always 1 second less than your input, so if you wanted to sleep for one second you would have to use the command SLEEP 2. That's not exactly ideal. Is there some way for me to pass the arithmetic of $1+1 and pass it on to the next command in Windows? I assume there is some way of using STDOUT...

    Read the article

  • Pointer position way off in Java Application menu's when using gnome-shell

    - by Hailwood
    When using any java application in gnome-shell if the window is maximised the pointer position is way off; but only on the menu's, in the editor, or the side panel, the pointer is fine. This only presents itself when the window is maximized, and it seems that the further away from 0x0 the window is when you maximise it, the bigger the pointer offset. From what I have gathered it has to do with the window not updating it's size when it gets maximised. The other issue is that when a gnome-shell notification appears, when clicking on it, I lose the ability to type in the editor, I can select text etc, but can't give it focus to type. I must bring up some other text input (e.g. right click on a file on the left, select rename, which brings up a rename dialog) after that I can type in the editor again. So, how can I fix this? Below is as much information as I can think to provide $ gnome-shell --version GNOME Shell 3.6.1 $ java -version java version "1.7.0_09" Java(TM) SE Runtime Environment (build 1.7.0_09-b05) Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode) $ file /etc/alternatives/java /etc/alternatives/javac /etc/alternatives/java: symbolic link to '/usr/lib/jvm/java-7-oracle/jre/bin/java' /etc/alternatives/javac: symbolic link to '/usr/lib/jvm/java-7-oracle/bin/javac'

    Read the article

  • Floating point arithmetic is too reliable.

    - by mcoolbeth
    I understand that floating point arithmetic as performed in modern computer systems is not always consistent with real arithmetic. I am trying to contrive a small C# program to demonstrate this. eg: static void Main(string[] args) { double x = 0, y = 0; x += 20013.8; x += 20012.7; y += 10016.4; y += 30010.1; Console.WriteLine("Result: "+ x + " " + y + " " + (x==y)); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } However, in this case, x and y are equal in the end. Is it possible for me to demonstrate the inconsistency of floating point arithmetic using a program of similar complexity, and without using any really crazy numbers? I would like, if possible, to avoid mathematically correct values that go more than a few places beyond the decimal point.

    Read the article

  • Why might different computers calculate different arithmetic results in VB.NET?

    - by Eyal
    I have some software written in VB.NET that performs a lot of calculations, mostly extracting jpegs to bitmaps and computing calculations on the pixels like convolutions and matrix multiplication. Different computers are giving me different results despite having identical inputs. What might be the reason? Edit: I can't provide the algorithm because it's proprietary but I can provide all the relevant operations: ULong \ ULong (Turuncating division) Bitmap.Load("filename.bmp') (Load a bitmap into memory) Bitmap.GetPixel(Integer, Integer) (Get a pixel's brightness) Double + Double Double * Double Math.Sqrt(Double) Math.PI Math.Cos(Double) ULong - ULong ULong * ULong ULong << ULong List.OrderBy(Of Double)(Func) Hmm... Is it possible that OrderBy is using a non-stable QuickSort and that QuickSort is using a random pivot? Edit: Just tested, nope. The sort is stable.

    Read the article

  • How to fix Emacs client *ERROR*: Arithmetic error

    - by nocash
    GNU Emacs 23.1.1 I've noticed that if I run Emacs and M-x server-start, I can use the emacsclient program as usual, but if if I start Emacs using emacs --daemon and then try to use emacsclient the new frame locks up and the shell outputs *ERROR*: Arithmetic error. This issue doesn't happen if I use the -t flag to force terminal mode when running emacsclient. Has anyone run into this before? Anyone know what's going on and/or how to fix it?

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question [closed]

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

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