UVa 562 runtime error. What can I do?

I am trying to solve Uva-562 - Dividing coins problem.My solution is giving runtime error.Error message:

Here is the error message: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at Main.main(Main.java:73)

This is my code:

package com.example.recursion;

import java.util.Scanner;

public class main {

    public static Scanner scanner;
    public static int[] binary;
    public static int[] set;
    public static int m;
    public static int total;
    public static int dp[][];

    public static void initDp(){

        dp=new int[101][50001];
        for(int i=0;i<101;i++)
            for(int j=0;j<50001;j++)
                dp[i][j]=-1;

    }

    public static void readcase() {

        m = scanner.nextInt();
        int i;
        total = 0;
        set=new int[101];

        for (i = 0; i < m; i++) {

            set[i] = scanner.nextInt();
            total += set[i];
        }
        int solution=solve(0,0);
        print(solution);


    }

    public static void print(int solution){

        System.out.println(solution);
    }

    public static int solve(int i, int sum1){

          int left=0,right=0;
          if(dp[i][sum1] > -1){
              return dp[i][sum1];
          }
          if(i==m){
                   int sum2;
                   sum2=total-sum1;
                   return Math.abs(sum1-sum2);
          }

          left=solve(i+1,sum1);
          right=solve(i+1, sum1+set[i]);


          if(left<right)
                   return dp[i][sum1]=left;
          else
                   return dp[i][sum1]=right;

      }

    public static void main(String args[]) {

        scanner = new Scanner(System.in);
        int n, i;
        n = scanner.nextInt();

        for (i = 0; i < n; i++) {

            initDp(); 
            readcase();
        }

    }

}

I have solved it.

The problem was NoSuchElementException for the line: n=scanner.nextInt(); I have fixed it using:

if(scanner.hasNextInt()) 
{
   n = scanner.nextInt();
}

The code has been accepted by uHunt.

链接地址: http://www.djcxy.com/p/96124.html

上一篇: npm安装irc失败

下一篇: UVa 562运行时错误。 我能做什么?