-2

I've made a simple game with 2 classes. It uses a scanner and when I try it it says java.util.NoSuchElementExeption. It also says the errors are on row 19 in RNGlog and 24 in RNG. Please help

First class: RNG

public class RNG {

public static void main(String[] args) {

    RNGlog log = new RNGlog();
    int max = log.max();
    int min = log.min();

    double counter = 3;
    //Variables outside of loop

    System.out.println("Write a number between " + max + " and " + min + ".");
    System.out.println("If your number is higher than " + max + ", it will be " + max + ". Vice versa for " + min + ".");
    System.out.println("If your number is higher than the random number, you win credits!");
    System.out.println("You start with 2 credits.");
    System.out.println("You lose if you hit 0 credits. Good luck!");
    //Introduction

    while(counter > 0) {
    //Loop start
        double r = Math.random() * 10;
        float in = log.getIn(); //Error here
        //Random number generator, input

        double credit = 6 - in;
        //Credit Win generator



        if(in > r) {

            counter = counter + credit;
            //Counter refresh

            System.out.println("Great job! The number was " + r + ".");
            System.out.println("You won " + credit + " credits. Nice.");
            System.out.println("Credit counter:" + counter + ".");
            //Winning messages

        }
        else  {

            counter = counter - 1;
            //Counter refresh

            System.out.println("Nearly, n00b! It was " + r + ", how did u no realize.");
            System.out.println("You lost 1 credits!");
            System.out.println("Credit counter:" + counter + ".");
            //Losing messages
        }

        if(counter <= 0) {              
            System.out.println("Game over! Better luck next time.");    
            //Game ender
        }

    }

}

}

Second class: RNGlog

import java.util.Scanner;

public class RNGlog {

int max() {
    int max = 6;
    return max;
}

int min() {
    int min = 0;
    return min;
}

float getIn() {
    Scanner scan = new Scanner(System.in);
    float imp = scan.nextFloat();   //Error here            

    if(imp < min()) {
        imp = min();            
    }
    //Stops number lower than 0

    if(imp > max()) {
        imp = max();
    }
    //Stops numbers higher than 6   
        scan.close();
    return imp;


}

}

Would be really apriciated if someone could help!

DivaKill
  • 67
  • 6

1 Answers1

1

NoSuchElementException : if the input is exhausted

you must test before with scanner.hasNext()

and if (scan.hasNextFloat())