user4895196
user4895196

Reputation:

type mismatch: cannot convert from double to Double

 import java.util.Scanner;
 public class merge_sort 
{
public static void main(String[] args) 
{
    Scanner input= new Scanner (System.in);
    System.out.println("Hello, how many numbers there should be in the array?");
    int Size=input.nextInt();
    Double A []=new Double [Size] ;
    System.out.println("Please enter "+ (Size+1)+" real numbers");
    for (int z=0;z<Size;z++)
        A[z]=input.nextDouble();
    int p=0,q=(Size/2+1),r=(Size-1);//assuming that the array with even length.
    int L []=new int [4] ;//the left side, sorted array
    int R []=new int [4] ;//the right side, sorted array
    L[0]=7;L[1]=6;L[2]=2;L[3]=1;
    R[0]=5;R[1]=4;R[2]=3;R[3]=8;
    for(int i=0;i<4;i++)
        System.out.print(L[i]);
    System.out.println("");
    for(int j=0;j<4;j++)
        System.out.print(R[j]);

 merge(L,R);        
}

I have an error in this line of the code:

A[z]=input.nextDouble();

The error is : type mismatch: cannot convert from double to Double

I am stuck couple of hours, can someone help me with that?

Upvotes: 1

Views: 8199

Answers (3)

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6836

There are two way to do this.

  1. By Invoking constructor of Double Class using new Operator and passing the input.nextDouble().

     A[z] = new Double(input.nextDouble());
    

2. A cool Feature introduced in and after java 1.5 named autoboxing So, You may also try this.

 A[z] = (Double)input.nextDouble();

Upvotes: 0

Đăng Khoa Huỳnh
Đăng Khoa Huỳnh

Reputation: 130

Such as Guy's answer, or you can change line:

A[z]=input.nextDouble();

to:

A[z]=new Double(input.nextDouble());

Upvotes: 0

Guy
Guy

Reputation: 50809

Double is a class type. nextDouble returns the primitive type double. Change A to double array

double[] A = new double[Size];

Upvotes: 2

Related Questions