1

I'm trying to scan a matix but I am coming with some error. Here is my code:

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {

    Scanner in=new Scanner(System.in);

    long a=in.nextLong();


// ERROR: incompatible types: possible lossy conversion from long to int


    long[][] b=new long[a][a];


    for(long i=0;i<a;i++){
        for(long j=0;j<a;j++)
            {
//same error here

            b[i][j]=in.nextLong();
        }
    }   
}
}
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107

4 Answers4

0

Just change it to this, initialization of a long variable should end with an L to specify that it is an long integer

for(long i=0L;i<a;i++){
    for(long j=0L;j<a;j++)

And also the initialisation to be casted to int than long

sameera sy
  • 1,708
  • 13
  • 19
0

I think the problem is when you read some value from keyboard.

 long a=in.nextLong();

Here you try read Long so in your keyboard add value with long format, like this: 1.0 or: https://stackoverflow.com/a/6834049/5877109

Community
  • 1
  • 1
eL_
  • 167
  • 2
  • 17
0

In the array declaration, you have to cast int to each of the array dimension sizes:

        long[][] b = new long[(int) a][(int) a];

The reason for this is that int is a variable type that only uses whole numbers: longs, doubles, floats, and other numerical variable types accept decimals, whereas int does not.

  • My problem solved but I have one doubt that if 'a' is long data type , what will happen? – Maitreya Patel Dec 07 '16 at 15:10
  • I do not understand. If the variable a is of type long, if that's what you mean, you have to cast it to some variable that will represent a whole number, or integer. In your code, you had "a" as a long data type. If "a" is left as a long, there's the possibility of a runtime error, for the scanner could include numbers past the decimal point. Hopefully that makes sense? – Ben Michalowicz Dec 10 '16 at 13:51
0

Use int instead long when you set a size of an array. And when you walk through it - use int for indices

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner in=new Scanner(System.in);

        int a=in.nextInt();

        long[][] b=new long[a][a];


        for(int i=0;i<a;i++){
            for(int j=0;j<a;j++)
            {    
                b[i][j]=in.nextLong();
            }
        }
    }
}
Michel_T.
  • 2,741
  • 5
  • 21
  • 31