Преобразовать ввод keyBd во ввод JOption и printf, println в сообщение JOption - PullRequest
0 голосов
/ 22 сентября 2018

Я пытаюсь понять и узнать, как перейти от простого ввода keyBD к использованию функции ввода / сообщения JOption.Исходный код выглядит следующим образом:

import java.util.Scanner;

открытый класс 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

Мне нужно заменить входные данные keyBD на JOptionPane, а распечатки на JOptionPane.Я также знаю, что все, что вводится, делается в виде строки и должно быть преобразовано в int.Я думаю, что я близко, но я не могу понять это заявление о конверсии.Вот мой обновленный код

import javax.swing.JOptionPane;

открытый класс 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);

}

}

Ответы [ 2 ]

0 голосов
/ 22 сентября 2018

это код, который я закончил, чтобы скомпилировать и выполнить.Будучи новичком в Java, если у вас возникнут вопросы, которые могут вызвать у меня проблемы в будущем или не будет наилучшей практикой, мне будет интересна обратная связь.спасибо.

import javax.swing.JOptionPane;

открытый класс Guess2 {

public static void main(String[] args) 
{
    //declare variables
  String answer;
  int myGuess;
  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  
  answer = JOptionPane.showInputDialog(null, "Enter a number between 1 and 25: ");
  myGuess = Integer.parseInt(answer);  

  while( myGuess != NUMBER_TO_GUESS)

    { 

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

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

    }//end while

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

}

}

0 голосов
/ 22 сентября 2018
JOptionPane.showInputDialog(null, "Enter a number between 1 and 25: ");
int myGuess = nextInteger.parseInt(myGuess); 

Как вы можете конвертировать "myGuess"?Откуда вы взяли начальное значение "myGuess"?

Что ж, ответ вы получили из панели параметров.Прочтите API JOPtionPane для получения информации о том, как использовать метод showInputDialog(...).Вы увидите, что метод возвращает значение.Поэтому вам нужно преобразовать строку в целое число:

String answer = (String)JOptionPane.showInputDialog(null, "Enter a number between 1 and 25: ");
int myGuess = nextInteger.parseInt(answer); 

Прочтите раздел из учебника Swing по Как создавать диалоги для получения дополнительной информации и рабочих примеров.

...