Reputation: 1465
I am trying to do something extremely basic! And it wont work :(. I feel like I'm going in circles.
Here's the rundown: I would like the user to input a series of numbers into an EditText box (separated by comma's). After the add button is selected a split method will separate each number into its own slot in a String[]. EVENTUALLY, if I can get this part to work, the numbers will be pulled out of the array and converted to doubles.Then they will be used in a calculation or two. I have tried several different ways of getting this done and it seems like the problem is coming from the split method or for-loop. The code listed below returns an empty string.
Also, through my trial and error I ended up with a return method calculate(). How much stuff can a cram in an onClick method? Was this a bad idea? Please be as a brutal as needed!!! I'm new to android. Thanks in advance.
package com.simplydesign.android.standarddev;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button addBtn = (Button) findViewById(R.id.addBtn);
final EditText userData = (EditText) findViewById(R.id.editText1);
final TextView dataCollection = (TextView) findViewById(R.id.textView1);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] rawData;
rawData = userData.getText().toString().split(",");
dataCollection.setText(calculate(rawData));
}
});
}
public String calculate(String[] a) {
String output = "";
for (int i = 0; i < a.length - 1; i++) {
output += " " + a[i];
} return output;
}
}
Upvotes: 0
Views: 1910
Reputation: 45253
The problem is in your for loop.
for (int i = 0; i < a.length - 1; i++) {
... should be ...
for (int i = 0; i < a.length; i++) {
I am guessing in all your tests, you were just using 2 number separated by commas, I spotted the problem as soon as I entered 3 numbers into your code.
Upvotes: 0
Reputation: 54705
In your for-loop you should iterate from 0 to a.length - 1
. This means the loop must look like:
for (int i = 0; i < a.length; i++) { /* ... */ }
But you'd better use something like that:
public String calculate(String[] a) {
StringBuilder output = new StringBuilder();
for (String s : a) {
output.append(' ').append(s);
}
return output.toString();
}
Unfortunately, I don't think it will completly solve your problem but it definitely fixes one error.
Upvotes: 2