【问题标题】:Return a valid value to the caller using a static method in Java使用 Java 中的静态方法将有效值返回给调用者
【发布时间】:2015-10-11 22:17:59
【问题描述】:

这是我的学校作业。我花了一整天的时间思考它,但失败了。我正在寻求有关 stackoverflow 的帮助。

问题是,每次提示用户输入四个整数并显示相应的消息,直到用户在提示输入 n 时输入值 0,这是终止执行的信号。另外,我需要包含一个静态方法:

int getAndVerifyInput (String userPrompt, int lowerBound, int upperBound)

提示用户输入一个值,验证它是否在所需的范围内(if-else 正确,如下所示)。必要时重新提示并重新输入,并返回一个有效值给调用者。

这是我的代码。

class AssignmentTwo
{
    public static void main(String[] args)
        {
            int n,i,j,k;    
            n = getAndVerfyInput("Enter size of circle, n", 0, Integer.MAX_VALUE);
            i = getAndVerfyInput("Enter first point(i)", 0, n);
            j = getAndVerfyInput("Enter second point(j)", 0, n);
            k = getAndVerfyInput("Enter third point(k)", i, j);

            if (n>0 && i>=0 && i<=n && j>=0 && j<=n && k>=0 && k<=n && i!=j &&
                    ((k<=i&&i<j)||(i<j&&j<k)||(j<k&&k<=i)))
                System.out.println("\nk lies on the arc from j to i when moving clockwise on a circle of size n.");
            else
                System.out.println("\nk does not lie on the arc from j to i when moving clockwise on a circle of size n.");
        }

    static int getAndVerfyInput(String userPrompt, int lowerBound, int upperBound)  // i j is lowerBound and upperBound
        {
            System.out.println(userPrompt);

            int result;

            Scanner keyboard = new Scanner(System.in);  
            result = keyboard.nextInt();

            return result;
        }
}

我的问题是我有四个变量(n,i,j,k),但是在 getAndVerifyInput 中只有两个变量,我不知道如何将 IF-ELSE 放入 getAndVerifyInput 方法中。

我教授的提示:getAndVerifyInput方法的第一个参数是字符串,比如第一次调用该方法,就是获取圆n的大小,第二次调用,就是获取i .等 j&k。

方法本身应该向用户显示第一个参数作为提示,然后输入用户的值,最后在将值返回给调用代码(main)之前验证是否在范围内。

【问题讨论】:

  • 你的问题是?
  • 我已添加到问题中。谢谢!
  • getAndVerifyInput 方法应该做什么?
  • 我补充了这个问题。比你巴尔温德!
  • 我还是没有看到问题...

标签: java methods return


【解决方案1】:

根据更新后的问题,您需要验证用户输入是否仍在lowerBoundupperBound 内。如果这是问题,那么您可以尝试将现有的getAndVerfyInput更改为以下内容:

static int getAndVerfyInput(String userPrompt, int lowerBound, int upperBound)
{


    int result;

    Scanner keyboard = new Scanner(System.in);  

    do{
        System.out.println(userPrompt);
        result = keyboard.nextInt();    

    } while (result < lowerBound || result > upperBound);



    return result;
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-10-17
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2013-06-09
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多