Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mismatch on data type? I converted all my ints to long?

import java.util.Random;
import java.util.Scanner;
public class ArrayPractice {
public static void main(String[] arg) {
    long input;
    System.out.println("How Many Times will you roll?");
    Random random=new Random();     
    Scanner scan=new Scanner(System.in);
    input=scan.nextLong();
    long freq[]=new long[7];
    for(long i=1;i<input;i++){
        //1+random.nextInt(6)-numbers 1-6
        ++freq[1+random.nextLong(6)];
    }
    System.out.println("Face\tFrequency");
    for(long i=1;i<freq.length;i++){
        System.out.println(i+"\t"+freq[i]);
    }
}
}

Why is my program saying that their is a mismatch at ++freq[1+random.nextLong(6)]; and freq[i]I converted all my values to long. Why should their be a mismatch?

like image 505
eli Avatar asked Dec 25 '22 08:12

eli


1 Answers

The array's indexes are of type int, while 1 + random.nextLong() will be evaluated as long, since random.nextLong() returns long.

Adding a cast should fix the problem:

++freq[(int) (1 + random.nextLong())];

or alternatively, you could fetch a random int:

++freq[1 + random.nextInt(6)];
like image 115
Konstantin Yovkov Avatar answered Jan 13 '23 05:01

Konstantin Yovkov