2017-03-19 17 views
-2

私は2つのクラスで簡単なゲームを作っています。それはスキャナを使用しています。試してみると、java.util.NoSuchElementExeptionと表示されます。また、エラーはRNGlogの19行目とRNGの24行にあるとも言われています。NoSuchElementExeptionをJavaで修正する方法

ファーストクラスを助けてください:誰かが助けることができれば本当にapriciatedだろう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; 


} 

}

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 
     } 

    } 

} 

}

セカンドクラスをRNG!

答えて

1

はNoSuchElementException:入力が

を使い果たしている場合は、scanner.hasNext(と前にテストする必要があります)

とIF(scan.hasNextFloat())

+0

おかげで、私はそれらを置く必要があり、私はしようとしたが、今はIllegalStateExeptionと言うから? – DivaKill

関連する問題