简体   繁体   中英

Storing into a Java Array through OnClickListener

I'm sorry if this comes through as a "noob" question, but I'm really stuck and I couldn't find any help, no matter where I looked.

The problem I'm having is this:

The user fills out a textbox saying how many numbers (doubles) he is going to input next (say n)

I store that number inside the OnClickListener method (that works ok)

public double n;
//CODE

n = Integer.parseInt(input.getText().toString());

I then need to store the n numbers that the user will input

He will fill out the textbox, press enter and the number should be stored in an array

Something like:

int i = n;
double x[] = new double[n];

button1.onClick(View view){
   x[i] = Double.parseDouble(input.getText().toString());
   i--;
}

No matter how I declare the x[i] I get an error message. I've done some debugging and the error pops up whenever storring in the array occurs. I know I'm missed out something basic about this and I feel pretty dumb for getting stuck with this, but I'd really appreciate any help or suggestion you guys might have.

Thanks a lot, Eugene

PS I have to declare the array AFTER "n" has been inputted, however when I try to use it in the next OnClickListener, it can't access it unless it's declared final, or as a class variable (public/private etc.)

double x[] = new double[n];

should be double[] x = new double[n];

Example:

public static void main(String[] args) {
        int n = 10;
        double[] x = new double[n];
        x[5] = 7;
        x[1] = 31;
        for(double i: x) {
            System.out.println(i);
        }
    }

Edit: You need to call i--; before x[i] = Double.parseDouble(input.getText().toString()); if you call new double[10] then only x[0] through x[9] are valid pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM