【问题标题】:Asking the user if they want to give multiple inputs询问用户是否要提供多个输入
【发布时间】:2013-10-28 03:05:39
【问题描述】:

我正在为 java 类的介绍进行分配,并且在考虑用户需要提供多个输入的情况时遇到了一些困难。问题如下:

"要求用户输入一个数字。你应该使用一个输入对话框来进行这个输入。一定要将对话框中的字符串转换为实数。程序需要跟踪用户的最小数字输入和输入的最大数字。询问用户是否要输入另一个数字。如果是,重复该过程。如果不是,输出用户输入的最小和最大数字。

当用户想退出时,这个程序在程序的末尾输出最大和最小的数字。

此外,您的程序应该考虑用户只输入一个数字的情况。在这种情况下,最小和最大的数字将是相同的。”

我的问题是我无法弄清楚如何让程序不断询问用户是否要输入另一个数字....就像他们说是一样多次(显然)。我知道我将不得不使用循环或其他东西,但我是一个初学者,不知道从哪里开始。任何帮助将不胜感激,并在此先感谢!

这是我目前所拥有的:

包查找最小值和最大值;

导入 javax.swing.JOptionPane;

公共类Findingminandmax {

public static void main(String[] args)
{   
       String a = JOptionPane.showInputDialog("Input a number:");
       int i = Integer.parseInt(a);

       String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");

       if ("yes".equals(b)) { 
        String c = JOptionPane.showInputDialog("Input another number:");
        int j = Integer.parseInt(c);

        int k = max(i, j);

       JOptionPane.showMessageDialog(null, "The maximum between " + i +
               " and " + j + " is " + k);

    }  else {
           JOptionPane.showMessageDialog(null, "The maximum number is " + i );
       }

}

public static int max(int num1, int num2) {
    int result;

    if (num1 > num2)
        result = num1;
    else
        result = num2;

    return result;
}

}

【问题讨论】:

标签: java loops input


【解决方案1】:
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
while(b.equalsIgnoreCase("yes")){
     String c = JOptionPane.showInputDialog("Input another number:");

     // your logic
     b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
}               
    // then have your logic to print maximum and minimum number

但要获得是/否输入,请使用确认对话框而不是输入对话框

例如

int b = JOptionPane.showConfirmDialog(null, "Would you like to input another number? yes or no", "More Inputs", JOptionPane.YES_NO_OPTION);
while (b == JOptionPane.YES_OPTION) {
    // your logic
}

【讨论】:

    【解决方案2】:
    while(true) {
        //do stuff
        if ("yes".equals(b)) {
            //do other stuff
        } else { break; }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 1970-01-01
      • 2023-03-05
      • 2022-08-18
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多