Access with the ENTER key

0

I need to spin the dice by pressing the Enter key, of which the operation is in another file. How can I do this?

public class Dice {

    public static void main(String[] args) {

        Printer.print("Press 'enter' to roll the dices");

    }
}

This is the code to turn the dice:

import java.util.Random;

public class Logic {

    public static void dice() {

        Random rnd = new Random();
        int dice1 = (int)(rnd.nextInt(6) + 1);
        int dice2 = (int)(rnd.nextInt(6) + 1);

        Printer.print("Dice 1 = " + dice1);
        Printer.print("Dice 2 = " + dice2);
        int sum = dice1 + dice2;

        Printer.print("Roll: total = " + sum);

    } 
}
    
asked by Neon 25.10.2016 в 18:39
source

1 answer

1

First you must detect when you press the% key% of%, this can be done by console through Scanner , comparing with equals the entry entered by the user. if it is ENTER it is interpreted that the key pressed was vacía (There are perhaps other ways to validate this)

Before you should ENTER a crear e Objeto tu Instanciar where is your method to spin the dice. (Take into account remove the Clase of your method static )

public void dice() {...}

public static void main(String[] args)  {
  Scanner t = new Scanner(System.in);
  /*Crear e Instanciar la clase de tu métod */
  Logic obj = new Logic();
  /* Entrada del Usuario */
   String enterkey = t.nextLine(); 
   /*Comparación para saber si se presiono Enter*/
  if (enterkey.isEmpty()) {
     /*Si es así , llamas a tu método girarDados */
      obj.dice();  
  }
}
    
answered by 25.10.2016 / 18:56
source