Reputation: 4232
I am trying to get a random values in string array. I want to display them in Textview. I wrote the code below. I am getting NumberFormatException.
Please help me!
How can I resolve my problem and how can I display random values in my textview?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int i1,i2,i3,i4,i5;
String [] strings;
TextView capta_Text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
capta_Text = (TextView)findViewById(R.id.captaid);
strings = new String [] {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
List<String> stringList = new ArrayList<String>(Arrays.asList(strings));
loadingCaptha();
}
private void loadingCaptha(){
try{
String randomStr = strings[new Random().nextInt(strings.length)];
int arc4random = Integer.parseInt(randomStr);
i1 = (arc4random % strings.length)-1;
i2 = (arc4random % strings.length)-1;
i3 = (arc4random % strings.length)-1;
i4 = (arc4random % strings.length)-1;
i5 = (arc4random % strings.length)-1;
String captaText = strings[i1]+""+strings[i2]+""+strings[i3]+""+strings[i4]+""+strings[i5];
capta_Text.setText(captaText);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 601
Reputation: 522171
The error seems fairly obvious to me from a quick glance at your code. Look at your strings
array definition:
strings = new String [] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
"d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C",
"D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
You included letters in there, and then you try to select one a parse it as an integer:
String randomStr = strings[new Random().nextInt(strings.length)];
int arc4random = Integer.parseInt(randomStr);
This won't work for obvious reasons. If you want to randomly select 5 letters from the strings
array to build your Captcha, then just do that:
Random rand = new Random();
i1 = rand.nextInt(strings.length);
i2 = rand.nextInt(strings.length);
i3 = rand.nextInt(strings.length);
i4 = rand.nextInt(strings.length);
i5 = rand.nextInt(strings.length);
String captaText = strings[i1]+""+strings[i2]+""+strings[i3]+""+strings[i4]+""+strings[i5];
capta_Text.setText(captaText);
Upvotes: 2