Reputation: 19
I want to create an app where the user has to guess the company name of an icon. Everything works fine but I want to have a button that prints a hint for the user. I want to print 1 random letter of the companys name. But the company name and the length of the name changes because of the different levels. So I thought I had to get the length of the companys name and then pick a random number of 0-companyname. Then I could use substring to chose 1 random letter of the companyname. But it doesnt work. Here the important parts my code:
Import java.util.Random;
int Laenge;
int BuchstabenPosition;
int DanachBuchstabenPosition;
Random r = new Random();
Laenge = companyName.length();
BuchstabenPosition = r.nextInt(Laenge);
DanachBuchstabenPosition = BuchstabenPosition += 1;
tvHint.setText("Ein Buchstabe: " + companyName.substring(BuchstabenPosition,DanachBuchstabenPosition));
When I run the app and click on the hint button, it only shows "Ein Buchstabe: ". I hope u understand what I want to do but here an example:
Level 1: Icon of YouTube, user doesnt have a clue of the company name, clicks hint button, a random letter of the word reveals, user now knows the name of the company and get to level 2.
Level 2: Icon of Stackoverflow, user doesnt have a clue of the company name, clicks hint button, a random letter of the word reveals.
If every company name would have the same length I could just make for example:
int BuchstabenPosition;
int DanachBuchstabenPosition;
Random r = new Random();
BuchstabenPosition = r.nextInt(8);
DanachBuchstabenPosition = BuchstabenPosition += 1;
tvHint.setText("Ein Buchstabe: " + companyName.substring(BuchstabenPosition,DanachBuchstabenPosition));
right? But the companyname length changes.
Upvotes: 0
Views: 82
Reputation: 2398
This line:
DanachBuchstabenPosition = BuchstabenPosition += 1;
Will first increment BuchstabenPosition
, then assign DanachBuchstabenPosition
to be the value of BuchstabenPosition
. So, BuchstabenPosition
and DanachBuchstabenPosition
are the same integer. The call to substring will then return the empty string ""
.
Instead assign DanachBuchstabenPosition
as this:
DanachBuchstabenPosition = BuchstabenPosition + 1;
So that it is 1 greater than BuchstabenPosition
.
Also, consider using charAt
instead, which is closer to what the logic of your code requires.
Upvotes: 2
Reputation: 2723
I would do:
String name = "Oracle";
Random random = new Random();
int index = random.nextInt(name.length());
char randomChar = name.charAt(index);
System.out.println("Index:" + index + " Letter:" + randomChar);
Upvotes: 1