samedi 22 septembre 2018

Convert keyBd input to JOption input and printf,println to JOption message

I'm trying to understand and learn how to go from a simple while if keyBD input to using the JOption input/message functionality. The original code looks like this:

import java.util.Scanner;

public class Guess2 {

public static void main(String[] args) 
{
    //keyboard scanner
    Scanner keyBd = new Scanner( System.in );

    //declare variables
int myGuess;
    final int NUMBER_TO_GUESS = 13;

//show introductory message
    System.out.print("\nWelcome to Guess-My-Number\nA GAME of CHANCE and SKILL\nLet's Play!\n\n");

//prompt to enter guess  
    System.out.print("Enter a number between 1 and 25: ");    
myGuess = keyBd.nextInt();
while( myGuess != NUMBER_TO_GUESS)
    {  
      //good or bad guess??
  if(myGuess < NUMBER_TO_GUESS) //too low
    System.out.printf("Your guess [ %d ] is too low...\nTry Again!\n", myGuess);
  else  //too high
    System.out.printf("Your guess [ %d ] is too high...\nTry Again!\n", myGuess);

    //prompt to enter guess  
        System.out.print("\nEnter a number between 1 and 25: ");    
    myGuess = keyBd.nextInt();
    }//end while

  //good guess
    System.out.printf(
        "Your guess [ %d ] is the number...\nCongratulations!\n", 
        myGuess);

}//end main()

}//end Guess1

I need want to replace the keyBD inputs with JOptionPane and the print outs with JOptionPane. I also know that anything that is inputted is done as a string and has to be converted to a int. I think I'm close but I can't figure out that conversion statement. Here is my updated code

import javax.swing.JOptionPane;

public class Guess2 {

public static void main(String[] args) 
{
    //declare variables
  final int NUMBER_TO_GUESS = 13;


//show introductory message
    JOptionPane.showMessageDialog(null, "\nWelcome to Guess-My-Number\nA GAME of CHANCE and SKILL\nLet's Play!\n\n");

//prompt to enter guess  
  JOptionPane.showInputDialog(null, "Enter a number between 1 and 25: ");
  int myGuess = nextInteger.parseInt(myGuess);  

  while( myGuess != NUMBER_TO_GUESS)

    { 

      //good or bad guess??
    if(myGuess < NUMBER_TO_GUESS) 
    //too low
    JOptionPane.showMessageDialog(null, "Your guess [ %d ] is too low...\nTry Again!\n", myGuess);
    else//too high
    JOptionPane.showMessageDialog(null, "Your guess [ %d ] is too high...\nTry Again!\n", myGuess);

    //prompt to enter guess  
    JOptionPane.showInputDialog(null, "Enter a number between 1 and 25: ");
  int myGuess = nextInteger.parseInt(myGuess);     

    }//end while

  //good guess
    JOptionPane.showMessageDialog(null, "Your guess [ %d ] is the number...\nCongratulations!\n", myGuess);

}

}

Aucun commentaire:

Enregistrer un commentaire