简体   繁体   中英

How to use method showMessage()?

In class we learned about methods, but I'm having a bit of trouble using them.

In a package called util, I wrote a class called IO.

public class IO {

    public static float getFloat(){
        String str = JOptionPane.showInputDialog("Enter a real number");
        return Float.parseFloat(str);
    }

    public static void showMessage(Scanner s){
        System.out.println(s);
        JOptionPane.showMessageDialog(null, s);
    }

    public static Scanner getInput (String prompt){
        String s = JOptionPane.showInputDialog(prompt);
        return new Scanner(s);
    }

}

Also in package util, I have my program, called Program 4.

public class Program4 {

    public static void main(String[] args) {
        IO.getInput("enter 2 integers");
        IO.showMessage(Scanner(s));    
    }
}

What I don't understand is how do I display the 2 integers entered? One is a scanner object and one is string. How do I use the method getInput to show convert the scanner into a string? Am I going to have to write a new method and use parse?

You can get user input without using Scanner . Here is example:

IO Class

public class IO {

    public static float getFloat() {
        String str = JOptionPane.showInputDialog("Enter a real number");
        return Float.parseFloat(str);
    }

    public static void showMessage(String s) {
        System.out.println(s);
        JOptionPane.showMessageDialog(null, s);
    }

    public static String getInput(String prompt) {
        // JOptionPane.showInputDialog() return user input String
        String input = JOptionPane.showInputDialog(prompt);
        return input;
    }

}

Program4 Class

public class Program4 {

    public static void main(String[] args) {
        // IO.getInput() return stored input String
        String input = IO.getInput("enter 2 integers");
        IO.showMessage(input);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM