What's wrong with Scanner?


  • 0
    L

    /**
    *I submit my code and it returns a runtime error: "Line 79: java.util.NoSuchElementException", the error code is "a = input.nextInt();"
    *I dont know why...
    */
    import java.util.Random;
    import java.util.Scanner;

    public class Solution {
    /**
    * Normal Guess
    * @params n the max number
    * */
    public static int getMoneyAmount(int n) {
    System.out.println("The number is from 1 to "+n);
    Random random = new Random();
    int aim = random.nextInt(n)+1;
    int i =inputNum(n);
    int sum=i;
    System.out.println("I guess :"+i);
    while(i!=aim){

    		if(i<aim){
    			System.out.println("it's higher");
    		}else{
    			System.out.println("it's lower");
    		}
    		i =inputNum(n);
    		System.out.println("I guess "+i);
    		sum+=i;
    	}
    	System.out.println("Yes, you are right.");
    	System.out.println("The number you pick from 1 to "+n+" is:"+i);
    	return sum;
    }
    /**
    * get input number
    */
    public static int inputNum(int n){
    	 int a =0;
    	  Scanner input = new Scanner(System.in);
    	  System.out.println("input the number you guess:");
    	  a = input.nextInt();
    	  if(a<0 || a>n){
    		  System.out.println("please enter the number between 0 to "+n);
    		  return inputNum(n);
    	  }
    	  return a;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.