Search code examples
javauser-interfaceif-statementinputjgrasp

creating a GUI input option


I want to create a GUI and script input option. So I need to add an input argument flag and program logic to use Scanner if false, JOptionPane if true. But I am having trouble doing this.

This is as far as i can get my code because I can't figure out how to get the if else statements and everything to work correctly.

import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Calendar;    

public class UtilsFL {


public static int readInt(String prompt) {
    Scanner input = new Scanner(System.in);
    int data;

    System.out.print(prompt);
    data = input.nextInt();

    return data;
}

Solution

  • It depends how you want to control your program: There is an example with variable, which can be changed in main() method if you call

    readInt("Please int",0)

    it will get int from Scanner, and if you call

    readInt("Please int",1)

    it will get int from JOptionPane.
    Otherwise it'll return -1

    There is missing catching exception

    public static int readInt(String prompt,int type) throws NumberFormatException{
        int data;
        switch(type){
             case 0:
                 Scanner input = new Scanner(System.in);
                 System.out.print(prompt);
                 data = input.nextInt();
                 input.close();
                 break;
             case 1:
                 data=Integer.parseInt(JOptionPane.showInputDialog(prompt));
                 break;
             default:
                 data=-1;
        }
        return data;
    }
    

    Not tested