dappers
dappers

Reputation: 23

Im trying to set a range of integers based on the users input

SO i am trying to use the obtained integers in my Math.Random but i get java.lang.string error

int secretNum;
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the guessing game. \n\nSet a range of numbers and the computer      will randomly generate a \nnumber between these numbers.Then you will try to guess the number!");
System.out.println("");
System.out.println("Please insert the lowest number in the range");
String low = input.nextLine();
System.out.println("Please insert the Maximum number in the range");
String max = input.nextLine();
secretNum = low + (int)(Math.random()*max);

Upvotes: 0

Views: 59

Answers (3)

R A Khan
R A Khan

Reputation: 187

Declare max not as String type but an Numeric(int or Integer) type. Like below

Integer max = Integer.parseInt(input.nextLine());

and also for low too.

Upvotes: 0

cschieb
cschieb

Reputation: 236

Instead of taking in the inputs as String, low and max should be ints, and therefore you could use

low = input.nextInt();

and

max = input.nextInt();

Upvotes: 0

August
August

Reputation: 12558

low and max are Strings, so they can't be used in arithmetic operations. Convert them to integers before using arithmetic:

secretNum = Integer.parseInt(low) + (int)(Math.random()* Integer.parseInt(max));

You could also get integers using Scanner#nextInt:

int low = input.nextInt();
int max = input.nextInt();

Upvotes: 1

Related Questions