2

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.

1

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

Use Integer.parseInt(String s):

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

Comments

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

Next time google it.

4 Comments

But if everyone did that, there would hardly be a reason for this site to exist. See how that works? This is a question/answer forum.
yeah but this is very very simple question :) I guess
try this :) google.com.pk/… a very simple query
@JJD I disagree. This site would not disappear if everyone googled for their answers first. Instead, the ratio of interesting/challenging questions to cruft would dramatically increase.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.