Java中的扫描仪输入问题

时间:2014-09-22 14:19:56

标签: java java.util.scanner

我是一名学习Java编程课程的学生。我的老师要求我们使用JOption窗格进行练习。我想我已经掌握了大部分内容,但却无法使其正常运行。我的程序不接受放在JOption窗格中的选项,但它在CMD窗口中接受它们。清除JOption窗格后接受选项。我的代码是:

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

public class Coffee10 {

    private static int item;
    private static double price;
    private static int menuNum;
    private static Scanner input;

    public static void main(String[] args) {
        calculateP();

        if (menuNum > 0) //calculateP(); going for 3 instances of input
        {
            if (menuNum > 0) //calculateP();
            {
                if (menuNum > 0) {
                    calculateP();
                }
            }
        }
    }

    public static double calculateP() {
        Scanner input = new Scanner(System.in);

        JOptionPane.showInputDialog(null, "Jivin' Java Coffee Shop" + "\nCoffee" + "\n(1)American     1.99" + "\n(2)Expresso      2.50" + "\n(3)Latte              2.15" + "\nMake selection. Press 0 to quit");
        JOptionPane.showInputDialog(null, "Jivin' Java Coffee Shop" + "\nCoffee" + "\n(1)American     1.99" + "\n(2)Expresso      2.50" + "\n(3)Latte              2.15" + "\nMake selection. Press 0 to quit");
        JOptionPane.showInputDialog(null, "Jivin' Java Coffee Shop" + "\nCoffee" + "\n(1)American     1.99" + "\n(2)Expresso      2.50" + "\n(3)Latte              2.15" + "\nMake selection. Press 0 to quit");
        JOptionPane.showMessageDialog(null, "Your total order comes to $" + price + ".");

        menuNum = input.nextInt();

        if (menuNum == 1) {
            item += 1;
            price += 1.99;
            return 1.99;
        } else if (menuNum == 2) {
            item += 1;
            price += 2.50;
            return 2.50;
        } else if (menuNum == 3) {
            item += 1;
            price += 2.15;
            return 2.15;
        } else {
            return 0;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您不能将ScannerJOptionPane.showInputDialog()一起使用。该方法具有用户输入的返回值。请参阅the javadoc

答案 1 :(得分:0)

您在Scanner上使用System.in女孩是标准输入AKA控制台,这就是为什么它在您使用控制台时适合您。要从JOptionPane获取输入,您必须存储JOptionPane.showInputDialog方法的返回值。此方法的返回值是用户输入

答案 2 :(得分:0)

如果你想从JOptionPane获取一个值,你应该使用它:

String result = JOptionPane.showInputDialog(null, "Jivin' Java Coffee Shop" + "\nCoffee" + "\n(1)American     1.99" + "\n(2)Expresso      2.50"
                + "\n(3)Latte              2.15" + "\nMake selection. Press 0 to quit");
if(result != null){
menuNum = Integer.parseInt(result);
}