Jimmy D
Jimmy D

Reputation: 5376

String to int in Java

I have a string named string1 that I read from a file. It's actually a number that I'm reading from the file. I now need to use that number in a random number generator. How can I do that?

String string1 = in.readLine();
Random generator = new Random();
int x = generator.nextInt(string1);

That obviously fails but I can't figure out how to make it work.

Upvotes: 2

Views: 250

Answers (3)

Haphazard
Haphazard

Reputation: 10948

Try int int1 = Integer.parseInt(string1);. Just make sure you do some error handling around that in case it is not an integer!

Upvotes: 4

Flo
Flo

Reputation: 27455

int num = Integer.valueOf(stringtext).intValue();

Next time google it.

Upvotes: 2

dacwe
dacwe

Reputation: 43504

Use Integer.parseInt(String s):

int max = Integer.parseInt(in.readLine());
Random generator = new Random();
int x = generator.nextInt(max);

Upvotes: 2

Related Questions