简体   繁体   中英

Exception in thread “main” java in mergesort

I have a question on what's going on, whenever I try to compile it it keeps giving me an error like this:

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864)

java.util.Scanner.next(Scanner.java:1485)

java.util.Scanner.nextInt(Scanner.java:2117)

java.util.Scanner.nextInt(Scanner.java:2076)

MergeSort.main(MergeSort.java:11)

import java.util.Random;
import java.util.*;
public class MergeSort
{
    static final int MAX=10005;
    static int[] a=new int[MAX];
    public static void main(String[] args) 
    {
    Scanner input = new Scanner("system.in");
    System.out.println("Enter MAx array size");
    int n = input.nextInt();
    Random random =new Random();
    System.out.println("Enter Array Elements");
    for(int i=0;i<n;i++)
        a[i]= random.nextInt(1000);
    long startTime =System.nanoTime();
    MergeSortAlgorithm(0,n-1);
    long stopTime =System.nanoTime();
    long elapsedTime =stopTime-startTime;
    System.out.println("Time Complexity in ms for n ="+n+(double)elapsedTime/1000000);
    System.out.println("Sorted Array(MergeSort):");

    for(int i=0;i<n;i++)
        System.out.println(a[i]+"");
    input.close();      
}       
public static void MergeSortAlgorithm(int low,int high)
{
    int mid ;
    if(low<high)
    {
        mid=(low+high)/2;
        MergeSortAlgorithm(low,mid);
        MergeSortAlgorithm(mid+1,high);
        Merge(low,mid,high);
    }
}   
public static void Merge(int low,int mid,int high)
{
    int[]b=new int[MAX];
    int i,h,j,k;
    h=i=low;
    j=mid+1;
    while((h<=mid)&&(j<=high))
        if(a[h]<a[j])
            b[i++]=a[h++];
        else
            b[i++]=a[j++];
        if(h>mid)
            for(k=j;k<=mid;k++)
                b[i++]=a[k];
}
}

You are using the wrong constructor for initializing the Scanner object in your code.

Unquote the String in the constructor of your Scanner object:

It should be like this:

Scanner input = new Scanner(System.in);

I was able to run your program after this.


PS: The error your are seeing is not a compile time error. You are probably getting it at run time.


Hope this helps!

Wrong syntax for scanner class.

Use it like:

  Scanner input = new Scanner(System.in);

For taking input from console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM